【问题标题】:SQL to ActiveRecord criteriaSQL 到 ActiveRecord 条件
【发布时间】:2013-12-10 12:28:02
【问题描述】:

我正在尝试在 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)
));

但这会导致以下错误:'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.

该列应该存在,这里有 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)

我到底做错了什么?

【问题讨论】:

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

标签: php sql activerecord yii


【解决方案1】:

您需要使用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'),

【讨论】:

  • 感谢您指出关系()的事情。你是对的。但是 CDbExpression 没有解决问题,并且 COALESCE 不需要。
【解决方案2】:

我已经设法解决了以下问题:将 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 在阵列部分帮助我。我仍然不完全确定为什么别名需要是现有的列名(在这种情况下,错误是 price 在 Table1 中不存在)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-20
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 2023-03-13
    • 1970-01-01
    • 2015-07-18
    相关资源
    最近更新 更多