joev
joev

Reputation: 13

Yii2 GridView Filtering on Relational Column not Responding

I am trying to filter on a relational data column.

In my search model, I added the field

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

Made it a safe search field

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

To the model's search function, I added a $query->joinWith

$query = CustomerProducts::find();

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

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

    $this->load($params);

And a ->andFilterWhere

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

The column does nothing when I try to filter. What am I doing wrong?

Upvotes: 1

Views: 645

Answers (1)

Jackson Tong
Jackson Tong

Reputation: 657

This is how I filter relational column

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

and use company_name attribute in your column definition.

Upvotes: 3

Related Questions