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值。但我正在'试图获取非对象的属性'

最佳答案

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

09-18 08:54