我一直在掙扎與下面的SQL轉換爲CDBCriteria與一個CActiveDataProvider使用:。 「SELECT PresetDeviceLink ,設備 FROM PresetDeviceLink INNER JOIN設備上Device.id = PresetDeviceLink。 DEVICEID WHERE Device.roomId = 1"警予CDbCriteria聯接列
表結構如下:
mysql> describe PresetDeviceLink;
+----------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| presetId | int(11) | NO | | NULL | |
| deviceId | int(11) | NO | | NULL | |
| state | int(11) | NO | | 0 | |
| value | int(11) | NO | | 32 | |
+----------+---------+------+-----+---------+----------------+
mysql> describe Device;
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| ref | int(11) | NO | | NULL | |
| roomId | int(11) | NO | | NULL | |
| typeId | int(11) | NO | | NULL | |
| paired | tinyint(1) | NO | | 0 | |
| name | varchar(255) | YES | | NULL | |
| description | text | YES | | NULL | |
| dimmerPos | int(11) | NO | | 0 | |
+-------------+--------------+------+-----+---------+----------------+
我在我的控制器代碼如下:
$criteria = new CDbCriteria;
$criteria->select = 'PresetDeviceLink.*, Device.*';
$criteria->join = 'INNER JOIN Device ON Device.id = PresetDeviceLink.deviceId';
$criteria->condition = 'Device.roomId = 1';
$presetDeviceLink=new CActiveDataProvider('PresetDeviceLink', array(
'criteria' => $criteria,
));
在運行時,我得到以下錯誤:
CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: <b>Column not
found</b>: 1054 Unknown column 'PresetDeviceLink.deviceId' in 'on clause'. The SQL
statement executed was: SELECT COUNT(*) FROM `PresetDeviceLink` `t` INNER JOIN
Device ON Device.id = PresetDeviceLink.deviceId WHERE Device.roomId = 1
奇怪的是,如果我使用「設備」作爲CActiveDataProvider源並更改連接語句連接到「PresetDeviceLink」,它就會抱怨說,無法找到Device.roomId列。
我只是不明白CActiveDataProvider是如何工作的?它在我看來,我只能使用表中的一個字段傳遞給CActiveDataProvider的條件(在連接或where子句中)。有什麼建議?
PS - SQL查詢在MySQL控制檯中運行得非常漂亮。
由於提前, 本
完美 - 謝謝。應該已經發現了別名,但是,我也會認爲這將在他們的文檔中提到!你的建議都奏效了。爲了清晰的代碼,我選擇了設置別名。謝謝您的幫助! – Ben 2012-04-24 17:47:14
我收回它 - 它在文檔中,不是很明顯。 http://www.yiiframework.com/doc/api/1.1/CDbCriteria - 在「別名」部分提到。 – Ben 2012-04-24 17:49:01