首页 文章

yii2多对多的where子句

提问于
浏览
0

我在Yii2中有很多关系,我想设置where子句但是框架说:未知列!

这是我的查找代码:

$rm = ProductHasAttValue::find()
                ->with('attValue')
                ->where('product_id='.$id." AND attValue.att_id=1") 
                ->all();

我确实attValue的表中有一个名为att_id的列 .

我为什么要在正确的位置设置?

提前致谢 ?

p.s:如果我不使用where子句并写下这个foreach,我可以得到att_id值..

foreach($rm as $ziizii){

            echo $ziizii->attValue->att_id."*";

}

型号:

here is my whole modle class :<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "att_value".
 *
 * @property integer $id
 * @property integer $att_id
 * @property string $value
 *
 * @property Att $att
 * @property ProductHasAttValue[] $productHasAttValues
 * @property Product[] $products
 */
class AttValue extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'att_value';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['att_id', 'value'], 'required'],
            [['id', 'att_id'], 'integer'],
            [['value'], 'string']
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'att_id' => 'Att ID',
            'value' => 'Value',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getAtt()
    {
        return $this->hasOne(Att::className(), ['id' => 'att_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProductHasAttValues()
    {
        return $this->hasMany(ProductHasAttValue::className(), ['att_value_id' => 'id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getProducts()
    {
        return $this->hasMany(Product::className(), ['id' => 'product_id'])->viaTable('product_has_att_value', ['att_value_id' => 'id']);
    }
}

1 回答

  • 3

    在where子句中它不应该是

    ->where('product_id='.$id." AND attValue.att_id=1")
    

    ->where('product_id='.$id." AND att_value.att_id=1")
    

    您应该将关系名称 attValue 替换为where子句中的相关表名

相关问题