我有两个表:
- 国家
- 城市
并且在模型中有关系。
为什么城市没有过滤器?
public function getCountry()
{
return $this->hasOne(Country::className(), ['id' => 'c_id']);
}
GridView
图片:
最佳答案
您可以通过简单地访问它来做到这一点:
'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')]);
================================ 或 ============== ===================
'columns' => [
[
'attribute' => 'countryFilter',
'value' => function($model) {
return $model->country->columnName;
}
]
]);
要过滤它,请在搜索类中添加自定义属性:
public $countryFilter;
在规则中添加:
public function rules()
{
return [
[['countryFilter'], 'safe'],
// ... more stuff here
];
}
在 search()
方法中添加与 Query
的关系:
->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
关于php - 如何在 GridView 上显示过滤模型关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45278944/