我遇到了Yii 2关系表的问题.我的工作有很多关系,但只有在这种情况下才会给我一个错误:
sqlSTATE[42S22]: Column not found: 1054 Unknown column ‘father.name’ in ‘where clause’
我认为问题是与同一个表“代理”的双重关系.查看模型中的代码段:
public function getAgent() { return $this->hasOne(Agent::className(),['id' => 'id_agent']); } public function getFather() { return $this->hasOne(Agent::className(),['id' => 'id_father']); }
在我的GridView中,我看到了正确的值,但是当我尝试使用ORDER或“andWhere”进行过滤时,Yii2会返回错误.
您可以在下面找到searchModel的代码:
$dataProvider->sort->attributes['agentName'] = [ 'asc' => ['agent.name' => SORT_ASC],'desc' => ['agent.name' => SORT_DESC],'default' => SORT_ASC ]; $dataProvider->sort->attributes['fatherName'] = [ //'asc' => ['father.name' => SORT_ASC],//'desc' => ['father.name' => SORT_DESC],'default' => SORT_ASC ]; //....... $query->andFilterWhere(['like','agent.name',$this->agentName]); $query->andFilterWhere(['like','father.name',$this->fatherName]);
agentName属性工作正常.
有什么建议吗?
谢谢!
——-更新:更多代码———
searchModel:
public function search($params) { $agent_aux = new Agent(); $agent_id= $agent_aux->getAgentIdFromUser(); if (Yii::$app->user->can('admin')){ $query = Contract::find(); } else{ $query = Contract::find()->where(['contract.agent_id' => $agent_id]); } $query->joinWith(['agent','seminar']); $dataProvider = new ActiveDataProvider([ 'query' => $query,]); $this->load($params); $dataProvider->sort->attributes['seminar_location'] = [ 'asc' => ['seminar.location' => SORT_ASC],'desc' => ['seminar.location' => SORT_DESC],]; $dataProvider->sort->attributes['agentName'] = [ 'asc' => ['agent.name' => SORT_ASC],'default' => SORT_ASC ]; $dataProvider->sort->attributes['fatherName'] = [ //'asc' => ['father.name' => SORT_ASC],'default' => SORT_ASC ]; if (!$this->validate()) { return $dataProvider; } $query->andFilterWhere([ 'id' => $this->id,'data' => $this->data,'id_agent' => $this->id_agent,'id_father' => $this->id_father,'id_seminar' => $this->id_seminar,]); $query->andFilterWhere(['like',$this->agentName]); $query->andFilterWhere(['like',$this->fatherName]); return $dataProvider; }
您需要在模型中进行以下更改. from子句实际上是在创建一个别名.代理人和父亲关系将在单独的连接条款中被选中.在过滤条件中使用“代理”和“父”别名与列名称.
原文链接:https://www.f2er.com/php/133753.htmlpublic function getAgent() { return $this->hasOne(Agent::className(),['id' => 'id_agent'])->from(['agent' => Agent::tableName()]); } public function getFather() { return $this->hasOne(Agent::className(),['id' => 'id_father'])->from(['father' => Agent::tableName()]) }
要改变的另一件事是
$query->joinWith(['agent','seminar','father']);