我正在使用基于我的表格的Gridview(我打电话给TABLE0
),我也有一个搜索表单。这里是我的表的样本和与之相关的其他表:来自JoinWith()的SQL与主ActiveQuery分离,使OnCondition()抛出未知的列错误
TABLE0
ID | TALBE1_ID | (more fields)
TABLE1
ID | TABLE2_ID | TABLE3_ID | (more fields)
TABLE2和表3:
ID | (more fields)
正如我们所见,TABLE1
与TABLE2
和TABLE3
都有关系。
我目前的问题是当我尝试使我的搜索表单。根据TABLE1
(在这种情况下,FIELDCHECK
)中的字段,我将使用其中一个搜索参数(在此例中为customAttribute
)从TABLE2
或TABLE3
(并且该列不具有相同名称)搜索特定列。
这里是我当前的搜索(不工作):
public customAttribute;
// more attributes, but not using at the moment
public function search($params)
{
$query = self::find()->orderBy(['TABLE0.FIELD0' => SORT_ASC]);
$dataProvider = new ActiveDataProvider([
'query' => $query
]);
$this->load($params);
if (!$this->validate()) {
$query->where('0=1');
return $dataProvider;
}
$query->joinWith([
'relationTable1' => function ($query1) {
$query1->andFilterWhere(['in', 'TABLE1.FIELDCHECK', ['0','1','2','3']])
// more ->andFilterWhere([]) but i'm not using at the moment
->joinWith([
'relationTable2' => function ($query2) {
$query2->onCondition(['TABLE1.FIELDCHECK' => '0']) // if FIELDCHECK is 0 i will do this join.
->andFilterWhere(['TABLE2.FIELD2' => $this->customAttribute]);
}
])
->joinWith([
'relationWithTable3' => function ($query3) {
$query3->onCondition(['<>', 'TABLE1.FIELDCHECK', '0']) // if FIELDCHECK is not 0 i will do this join instead
->andFilterWhere(['TABLE3.FIELD3' => $this->customAttribute]);
}
]);
}
]);
return $dataProvider;
}
这是抛出一个SQL错误:
General error: 4104 General SQL Server error: Check messages from the SQL Server [4104] (severity 16) [(null)]
The SQL being executed was: SELECT * FROM [TABLE2] WHERE ([ID] IN ('163203002', '163202002', '163203001', '163203004', '163203003', '163202001', '163202003', '163202004', '161201005', '161201012', '161201020', '161201021', '161201022', '161201023', '161201034', '161201042', '161201043', '161201046', '161201701', '161201047')) AND ([TABLE1].[FIELDCHECK]='0')
好了,有了这个错误,我可以看到joinWith
SQL是运行分离从主查询(在获得ID之后)。但是,如果我试图让这个$query
与$query->createCommand()->sql
生成的SQL我得到:
SELECT [TABLE0].* FROM [TABLE0]
LEFT JOIN [TABLE1] ON [TABLE0].[TABLE1_ID] = [TABLE1].[ID]
LEFT JOIN [TABLE2] ON ([TABLE1].[TABLE2_ID] = [TABLE2].[ID]) AND ([TABLE1].[FIELDCHECK] = '0')
LEFT JOIN [TABLE3] ON ([TABLE1].[TABLE3_ID] = [TABLE2].[ID]) AND ([TABLE1].[FIELDCHECK] <> '0')
WHERE [TABLE1].[FIELDCHECK] IN ('0','1','2','3') ORDER BY [TABLE0].[FIELD0];
并运行此查询,它工作正常。我知道我可以尝试在这个Gridview中使用原始的sql(可能与ArrayDataProvider,但我仍然不知道如何),但我真的想使这个ActiveDataProvider
工作。
我删除了所有不相关的代码,但我在代码中留了言。