mysql连接表并接收一行

时间:2016-07-05 05:45:20

标签: php mysql sql yii

The table 'category':

cat_id   category
1        mobile
2        watch
..        .. 

和' category_brand'表:

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;
   }

我试图重新检索product_id的类别。我在这做错了什么? product_id是auto_increment值。但我正在试图获得非对象的财产

1 个答案:

答案 0 :(得分:0)

queryOne()返回array|false,而不是ActiveRecord对象

查看print_r($editcat);

的结果

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

如果您想要AR对象作为结果,请使用其实现

$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();

或尝试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();