2012-04-23 71 views
0

我一直在挣扎与下面的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控制台中运行得非常漂亮。

由于提前, 本

回答

1

由于是在可见的“执行的SQL语句是:”行,第一表是别名为t。这是Yii的标准行为。

由于这个原因,您应该使用该别名来引用该表而不是PresetDeviceLink。或者你可以尝试设置$criteria->alias = 'PresetDeviceLink';,然后在CActiveDataProvider中使用它,尽管我没有亲自尝试过这个选项,它应该可以工作。

+0

完美 - 谢谢。应该已经发现了别名,但是,我也会认为这将在他们的文档中提到!你的建议都奏效了。为了清晰的代码,我选择了设置别名。谢谢您的帮助! – Ben 2012-04-24 17:47:14

+1

我收回它 - 它在文档中,不是很明显。 http://www.yiiframework.com/doc/api/1.1/CDbCriteria - 在“别名”部分提到。 – Ben 2012-04-24 17:49:01