2016-07-05 74 views
1
The table 'category': 

cat_id category 
1  mobile 
2  watch 
..  .. 

和 'category_brand' 表:MySQL的加入表和接收一行

product_id cat_id 
1    1 
2    1 
3    2 
..    .. 

,我有这样的代码

public function actionEdit($id) 
    { 
     $sql="SELECT * FROM category_brand INNER JOIN category ON category_brand.cat_id=category.cat_id WHERE category_brand.product_id=$id"; 
     $editcat=Yii::$app->db->createCommand($sql)->queryOne(); 
     print_r($editcat->category);die; 
    } 

我想retreice的PRODUCT_ID的范畴。我在这里做错了什么? product_id是auto_increment值。但我得到“试图获得非对象的特性”如果你想AR对象作为结果

+2

您的查询看起来不错,这将离开谊代码作为该错误的嫌疑。 –

回答

0

queryOne()回报array|false,不ActiveRecord对象

起来看看print_r($editcat);

http://www.yiiframework.com/doc-2.0/yii-db-command.html#queryOne()-detail

结果,使用它的真实性

$editCategory = Category::find() 
     ->joinWith(['categoryBrand']) // hasOne relation declared in Category model 
     ->where([ 
     category_brand.product_id=:id //category_brand is table name 
     ]) 
     ->params([':id'=>$id]) 
     ->one(); 

或t RY findBySql()

$editCategory = Category::findBySql("SELECT * FROM category INNER JOIN category_brand ON category_brand.cat_id=category.cat_id WHERE category_brand.product_id=:id",['id'=>$id])->one();

+0

好的。我也可以用'print_r($ editcat ['category']);''来完成它 – micky