使用 Yii2 中的关系在 GridView 列中搜索

Searching in GridView column with relation in Yii2(使用 Yii2 中的关系在 GridView 列中搜索)
本文介绍了使用 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.

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

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Convert JSON integers and floats to strings(将JSON整数和浮点数转换为字符串)
in php how do I use preg replace to turn a url into a tinyurl(在php中,如何使用preg替换将URL转换为TinyURL)
all day appointment for ics calendar file wont work(ICS日历文件的全天约会不起作用)
trim function is giving unexpected values php(Trim函数提供了意外的值php)
Basic PDO connection to MySQL(到MySQL的基本PDO连接)
PHP number_format returns 1.00(Php number_Format返回1.00)