2013-11-25 35 views
4

我试图重现一个ActiveRecord标准的SQL语句:SQL ActiveRecord不同标准

SELECT COALESCE(price, standardprice) AS price 
FROM table1 
LEFT JOIN table2 
ON (pkTable1= fkTable1) 
WHERE pkTable1= 1 

到目前为止,我有以下几点:

$price = Table1::model()->find(array(
    "select" => "COALESCE(price, standardprice) AS price", 
    'with' => array(
     'table2' => array(
      'joinType' => 'LEFT JOIN', 
      'on' => 'pkTable1= fkTable1', 
     ) 
    ), 
    'condition' => 'pkTable1=:item_id', 
    'params' => array(':item_id' => 1) 
)); 

但这会导致到以下错误:'Active record "Table1" is trying to select an invalid column "COALESCE(price". Note, the column must exist in the table or be an expression with alias.

虽然列应该存在,但下面是两个表结构:

表1

pkTable1  int(11) - Primary key 
standardprice decimal(11,2) 
name   varchar(255) //not important here 
category  varchar(255) //not important here 

表2

pkTable2  int(11) - Primary key //not important here 
fkType   int(11) - Foreign key //not important here 
fkTable1  int(11) - Foreign key, linking to Table1 
price   decimal(11,2) 

我究竟在做什么错?

+2

尝试替换您的选择,如下所示:'“select”=> array(“COALESCE(price,standardprice)AS price”)'。这可能有助于理解逗号不是列分隔符。 –

回答

0

我已经设法解决这个问题,如下所示:将COALESCE表达式包装在数组中,并将别名更改为表中现有的列名。

$price = Table1::model()->find(array(
    "select" => array("COALESCE(price, standardprice) AS standardprice"), 
    'with' => array(
     'table2' => array(
      'joinType' => 'LEFT JOIN', 
      'on' => 'pkTable1= fkTable1', 
     ) 
    ), 
    'condition' => 'pkTable1=:item_id', 
    'params' => array(':item_id' => 1) 
)); 

感谢Willemn Renzema帮助我完成阵列部分。我仍然不完全确定为什么别名需要是现有的列名称(在这种情况下,表1中不存在price的错误)。

1

您将需要使用一个CDbExpressionCOALESCE()表达:

$price=Table1::model()->find(array(
    'select'=>array(
     new CDbExpression('COALESCE(price, standardprice) AS price'), 
    ), 
    'with' => array(
     'table2' => array(
      'joinType'=>'LEFT JOIN', 
      'on'=>'pkTable1=fkTable1', 
     ), 
    ), 
    'condition'=>'pkTable1=:item_id', 
    'params'=>array(':item_id'=>1) 
)); 

我进一步相信,如果table2已经在你的表1模型relations()方法被挂,以下行应该足够了:

'with'=>array('table2'), 
+0

谢谢你指出关系()的东西。你是对的。但是CDbExpression并没有解决这个问题,对于COALESCE来说也不需要。 –

+0

真的吗?呃,我可以*宣誓* CDbExpression'这是必要的... – DaSourcerer