php – SQL到ActiveRecord标准
发布时间:2020-12-13 22:50:38 所属栏目:PHP教程 来源:网络整理
导读:我试图在ActiveRecord标准中重现以下SQL: SELECT COALESCE(price,standardprice) AS priceFROM table1LEFT JOIN table2ON (pkTable1= fkTable1)WHERE pkTable1= 1 到目前为止,我有以下内容: $price = Table1::model()-find(array( "select" = "COALESCE(pr
我试图在ActiveRecord标准中重现以下SQL:
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) )); 但这导致以下错误:’活动记录“Table1”正在尝试选择无效列“COALESCE(价格”.注意,该列必须存在于表中或者是带别名的表达式. 该列应该存在,这里是2个表结构: 表格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) 我究竟做错了什么? 解决方法
您需要使用
CDbExpression 作为COALESCE()表达式:
$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已经在Table1模型的relations()方法中链接,则以下行应该足够了: 'with'=>array('table2'), (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |