关联模型上的 Yii2 过滤器,其中关系名称为小驼峰式 [英] Yii2 filter on related model where relation name is lower camelCase

查看:20
本文介绍了关联模型上的 Yii2 过滤器,其中关系名称为小驼峰式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经成功地实现了 http://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview/.在我的关系名称只是一个单词的情况下,它一直工作正常.但是我的关系名称类似于 subSector 我得到:Column not found: 1054 Unknown column 'subSector.sub_sector' in 'where clause'.

I've successfully been working through implementing http://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview/. Which has been working fine where my relation name is just a single word. But where my relation name is something like subSector I'm getting: Column not found: 1054 Unknown column 'subSector.sub_sector' in 'where clause'.

public function search($params)
{
    $query = Product::find();
    // add in relation to be able to search with
    $query->joinWith(['sector', 'subSector'];
...
$dataProvider->sort->attributes['sub_sector_search'] = [
    // The tables are the ones our relation are configured to
    'asc' => ['subSector.sub_sector' => SORT_ASC],
    'desc' => ['subSector.sub_sector' => SORT_DESC],
    ];
...
$query->andFilterWhere([
'product_id' => $this->product_id,
...
])
->andFilterWhere(['like', 'subSector.sub_sector', $this->sub_sector_search])

我还在类初始化下面添加了参数,并在规则中添加了安全术语.

I've also added the parameter below the class initialization and added the safe term in the rules.

到目前为止,所有 3 个单词关系都适用于过滤,并且驼峰式大小写的模型关系都返回 unknown column.

So far all 3 single word relations work for filtering and both model relations that are camelCase return unknown column.

推荐答案

改用这个:

->andFilterWhere(['like', Subsector::tableName() . '.sub_sector', $this->sub_sector_search])

等等.

这将解决重复列的问题,如果表名将来会发生变化,您只需要更改模型中的 tableName() 方法,而无需在所有过滤器等中替换它.

This will resolve duplicate columns problem and if the table name will change in the future, you just only need to change tableName() method in your model without replacing it in all filters, etc.

Framework 将此解释为:'subSector.sub_sector' 只是以表名为前缀的列名,因此如果您的表命名与 subSector 不同,例如 subsectors,它不会工作.

Framework interprets this: 'subSector.sub_sector' as just column name prefixed with table name, so if your table named differently than subSector, for example subsectors, it won't work.

这篇关于关联模型上的 Yii2 过滤器,其中关系名称为小驼峰式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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