如何在GridView上显示过滤模型关系

时间:2017-07-24 11:03:41

标签: php gridview activerecord yii yii2

我有两张桌子:

  • 国家

并且在模特中有关系。

为什么城市没有过滤器?

public function getCountry()
{
    return $this->hasOne(Country::className(), ['id' => 'c_id']);
}

GridView图片:

GridView Image

1 个答案:

答案 0 :(得分:1)

您可以通过简单地访问它来执行此操作:

'columns'=>[
   'country.columnName',
]);

在模型覆盖attributes()函数中:

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

将其添加到规则:

public function rules()
{
     return [
         [['country.columnName'], 'safe'],
            // ... more stuff here
     ];
}

search()方法中,将其添加到Query

$query->andFilterWhere(['LIKE', 'country.columnName', $this->getAttribute('country.columnName')]);

================================ OR ============== ===================

'columns' => [
   [
       'attribute' => 'countryFilter',
       'value' => function($model) {
           return $model->country->columnName;
        }
   ]
]);

要过滤它,请添加自定义属性执行搜索类:

public $countryFilter;

在规则中添加:

public function rules()
{
     return [
         [['countryFilter'], 'safe'],
            // ... more stuff here
     ];
}

Query方法中添加与search()的关系:

->joinWith(['country'])

然后将过滤内容添加到Query

->andFilterWhere(['like', 'country.columnName', $this->countryFilter])

要对其进行排序,请添加:

$dataProvider->sort->attributes['countryFilter'] = [
                'asc'  => ['country.columnName' => SORT_ASC],
                'desc' => ['country.columnName' => SORT_DESC],
            ];

更多信息可在文档中找到:Displaying & sorting relational data