Searching in GridView column with relation in Yii2

旧城冷巷雨未停 提交于 2019-12-06 10:52:00

问题


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

And in search model (search() function) I add:

$query->joinWith('city');
$query->andFilterWhere(['like', 'cities.title', $this->city_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',
]);

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.


回答1:


do not forget to add region_id to your search model.



来源:https://stackoverflow.com/questions/34394565/searching-in-gridview-column-with-relation-in-yii2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!