在Yii2中在GridView列中搜索相关关系 [英] Searching in GridView column with relation in Yii2

查看:142
本文介绍了在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具有引用Regions(id)的外键region_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,因此可以通过city进行检索. 我将不胜感激.

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.

这篇关于在Yii2中在GridView列中搜索相关关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆