关系列上没有响应的Yii2 GridView过滤

时间:2017-03-17 12:48:14

标签: gridview yii2 yii2-basic-app

我正在尝试过滤关系数据列。

在我的搜索模型中,我添加了字段

public function attributes()
{        
    // add related fields to searchable attributes
    return array_merge(parent::attributes(), ['customerProductBaseProduct.product_name');
}

使其成为一个安全的搜索领域

['customerProductBaseProduct.product_name'], 'safe'],

对于模型的搜索功能,我添加了一个$ query-> joinWith

$query = CustomerProducts::find();

    // add conditions that should always apply here
    $query->joinWith(['customerProductBaseProduct']);

    $dataProvider = new ActiveDataProvider([
        'query' => $query,
    ]);

    $this->load($params);

并且 - >和.FilterWhere

$query->andFilterWhere(['like', 'customer_product_customerID', $this->customer_product_customerID])
        ->andFilterWhere(['like', 'customer_product_formula', $this->customer_product_formula])
        ->andFilterWhere(['like', 'customer_product_name', $this->customer_product_name])
        ->andFilterWhere(['like', 'customer_product_sub_name', $this->customer_product_sub_name])
        ->andFilterWhere(['like', 'customer_product_spanish', $this->customer_product_spanish])
        ->andFilterWhere(['like', 'customer_product_category', $this->customer_product_category])
        ->andFilterWhere(['like', 'customerProductBaseProduct.product_name', $this->customerProductBaseProduct]);

当我尝试过滤时,该列无效。我做错了什么?

1 个答案:

答案 0 :(得分:3)

这是我过滤关系列的方法

class UserSearch extends User
{
    public $company_name;
    public function rules()
    {
        return [
            [['first_name', 'last_name', 'email', 'company_name'], 'safe']
        ];
    }

    public function search()
    {
        $query = User::find();
        $query->joinWith(['client c']); //set relation alias

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        if (!($this->load($params) && $this->validate())) {
            return $dataProvider;
        }

        $query
            ->andFilterWhere(['like', 'first_name', $this->first_name])
            ->andFilterWhere(['like', 'last_name', $this->last_name])
            ->andFilterWhere(['like', 'email', $this->email])
            ->andFilterWhere(['like', "c.company_name", $this->company_name]);

        return $dataProvider;
    }
}

并在列定义中使用company_name属性。