php - SQL 到 ActiveRecord 条件

标签 php sql activerecord yii

我正在尝试在 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(price)”。注意,该列必须存在于表中或者是带别名的表达式。

虽然该列应该存在,但这是 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'),

关于php - SQL 到 ActiveRecord 条件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198838/

相关文章:

php - 展开数组并删除前缀

sql - 如何在 Sql 中设计 oauth 2.0 访问 token 字段?

sql server 2008 按问题排序

python - 惰性评估是如何实现的(例如在 ORM 中)

ruby-on-rails - Rails update_attribute 没有保存

php - Laravel的上下迁移方法如何工作?

php - 在网站上显示 pdf

sql - Oracle APEX 主详细信息页面创建 : ORA-06531 error

ruby-on-rails - 使用事件记录查询从 postgres 数据库返回不同或分组的记录

PHP CURL 登录和下载文件代码不起作用