2016-07-05 71 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