简体   繁体   English

关系名称为低驼色的相关模型的Yii2过滤器

[英]Yii2 filter on related model where relation name is lower camelCase

I've successfully been working through implementing http://www.yiiframework.com/wiki/653/displaying-sorting-and-filtering-model-relations-on-a-gridview/ . 我已经成功地实现了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' . 但是,在我的关系名称类似于subSectorColumn 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. 我还在类初始化下面添加了参数,并在规则中添加了安全术语。

So far all 3 single word relations work for filtering and both model relations that are camelCase return unknown column . 到目前为止,所有3个单词关系都可以进行过滤,而camelCase的两个模型关系都返回unknown column

Use this instead: 使用此代替:

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

and so on. 等等。

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. 这将解决重复列的问题,并且如果表名将来会更改,则只需要在模型中更改tableName()方法,而无需在所有过滤器中替换它,等等。

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. 框架将以下'subSector.sub_sector'为: 'subSector.sub_sector'只是以表名作为前缀的列名,因此,如果您的表的名称不同于subSector ,例如subsectors ,它将无法正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM