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

2023-10-15php开发问题
1

本文介绍了使用 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 列中搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

PHP实现DeepL翻译API调用
DeepL的翻译效果还是很强大的,如果我们要用php实现DeepL翻译调用,该怎么办呢?以下是代码示例,希望能够帮到需要的朋友。 在这里需要注意,这个DeepL的账户和api申请比较难,不支持中国大陆申请,需要拥有香港或者海外信用卡才行,没账号的话,目前某宝可以...
2025-08-20 php开发问题
168

PHP通过phpspreadsheet导入Excel日期数据处理方法
PHP通过phpspreadsheet导入Excel日期,导入系统后,全部变为了4开头的几位数字,这是为什么呢?原因很简单,将Excel的时间设置问文本,我们就能看到该日期本来的数值,上图对应的数值为: 要怎么解决呢?进行数据转换就行,这里可以封装方法,或者用第三方的...
2024-10-23 php开发问题
287

mediatemple - 无法使用 codeigniter 发送电子邮件
mediatemple - can#39;t send email using codeigniter(mediatemple - 无法使用 codeigniter 发送电子邮件)...
2024-08-23 php开发问题
11

Laravel Gmail 配置错误
Laravel Gmail Configuration Error(Laravel Gmail 配置错误)...
2024-08-23 php开发问题
16

将 PHPMailer 用于 SMTP 的问题
Problem with using PHPMailer for SMTP(将 PHPMailer 用于 SMTP 的问题)...
2024-08-23 php开发问题
4

关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题
Issue on how to setup SMTP using PHPMailer in GoDaddy server(关于如何在 GoDaddy 服务器中使用 PHPMailer 设置 SMTP 的问题)...
2024-08-23 php开发问题
17