问题
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.
So far all 3 single word relations work for filtering and both model relations that are camelCase return unknown column
.
回答1:
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.
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.
来源:https://stackoverflow.com/questions/34468405/yii2-filter-on-related-model-where-relation-name-is-lower-camelcase