使用 Yii2 中的关系在 GridView 列中搜索
我有一个带有外键 city_id
的模型,它引用了表 Cities (id)
.在 GridView
中,我显示城市标题而不是 id,并且我知道如何添加搜索带有外键的列,即在视图中:
I have a model with foreign key city_id
that references table Cities (id)
. In the GridView
I show city title instead of id, and I know how to add searching for column with foreign key, i.e, in view:
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
//some columns
[
'attribute' => 'city_id',
'value'=>'city.title
],
]);
并在搜索模型(search()
函数)中添加:
And in search model (search()
function) I add:
$query->joinWith('city');
$query->andFilterWhere(['like', 'cities.title', $this->city_id]);
而且它工作正常.但我也想在我的网格中显示 region
,我的表 Cities
有一个外键 region_id
引用 Regions(id)代码>.我在网格中添加了区域标题:
And it works fine. But I also want to show region
in my grid, and my table Cities
has a foreign key region_id
which references Regions(id)
.
I added the region title to the grid:
GridView::widget([
'dataProvider' => $dataProvider,
'filterModel' => $searchModel,
'columns' => [
//some columns
[
'attribute' => 'city_id',
'value'=>'city.title
],
'city.region.title_en',
]);
现在我不知道如何添加搜索以及如何更改search()
函数,因为我的主模型中没有region_id
,我通过城市代码>.如有任何建议,我将不胜感激.
Now I dont know how to add searching and how to change search()
function, because I dont have region_id
in my main model, I retrieve it through city
.
I would appreciate any advise.
推荐答案
不要忘记将 region_id
添加到您的搜索模型中.
do not forget to add region_id
to your search model.
相关文章