我遇到了Yii 2关系表的问题。我的工作有很多关系,但只有在这种情况下才会给我一个错误:
SQLSTATE [42S22]:未找到列:1054未知列' father.name'在' where子句'
我认为问题是与同一个表"代理"的双重关系。查看模型中的代码片段:
CREATE TABLE data
(
groupId int not null,
startTime datetime not null,
endTime datetime not null
)
INSERT INTO Data (groupId, startTime, endTime)
VALUES (1022, '2015-09-14 06:30:00.000', '2015-09-14 13:45:00.000')
INSERT INTO Data (groupId, startTime, endTime)
VALUES (1022, '2015-09-14 11:20:00.000', '2015-09-14 11:50:00.000')
INSERT INTO Data (groupId, startTime, endTime)
VALUES (1477, '2015-09-14 09:46:00.000', '2015-09-14 16:13:00.000')
INSERT INTO Data (groupId, startTime, endTime)
VALUES (1477, '2015-09-14 13:40:00.000', '2015-09-14 14:10:00.000')
INSERT INTO Data (groupId, startTime, endTime)
VALUES (2037, '2015-09-14 09:43:00.000', '2015-09-14 12:00:00.000')
INSERT INTO Data (groupId, startTime, endTime)
VALUES (2037, '2015-09-14 12:00:00.000', '2015-09-14 19:02:00.000')
INSERT INTO Data (groupId, startTime, endTime)
VALUES (2037, '2015-09-14 14:00:00.000', '2015-09-14 14:30:00.000')
在我的GridView中,我看到了正确的值,但是当我尝试使用ORDER或"以及"进行过滤时,Yii2会返回错误。
您可以在下面找到searchModel的代码:
public function getAgent()
{
return $this->hasOne(Agent::className(), ['id' => 'id_agent']);
}
public function getFather()
{
return $this->hasOne(Agent::className(), ['id' => 'id_father']);
}
agentName属性工作正常。 有什么建议吗? 谢谢!
-------更新:更多代码--------- 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]);
答案 0 :(得分:14)
您需要在模型中进行以下更改。 from子句实际上是在创建一个别名。代理人和父亲关系将在单独的连接条款中被选中。在过滤条件中使用“agent”和“father”别名,并使用列名。
public 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']);
答案 1 :(得分:1)
@FidoXLNC答案的替代方法可能是在您进行连接时定义别名:
chart.setDrawGridBackground(false);
xAxis.setDrawGridLines(false);
xAxis.setDrawAxisLine(false);
yAxisleft.setDrawGridLines(false);
yAxisleft.setDrawAxisLine(false);
yAxisright.setDrawGridLines(false);
yAxisright.setDrawAxisLine(false);
但是AFAIK你必须指定两种关系,而不仅仅是一种。