无效列错误 - 必须存在于 table 中或者是带有别名的表达式 (Yii 1.x)

Invalid column error - must exist in table or be an expression with alias (Yii 1.x)

在模型中我有以下逻辑:

$criteria = new CDbCriteria();
$criteria->select = 'COALESCE(oca.reason, ocd.reason) AS reward_name, SUM(t.points) AS points, COUNT(t.redeemed_code_id) AS totalCount';
$criteria->join = 'LEFT JOIN organisation_classroom_deductions ocd ON ocd.deduction_id = t.order_product_id AND t.type = 1
                   LEFT JOIN organisation_classroom_achievements oca ON oca.achievement_id = t.order_product_id AND t.type = 2
                   LEFT JOIN myuser ON (myuser.user_id = t.myuser_id)';
$criteria->condition = 'myuser.organisation_id ='. user()->data->organisation->organisation_id;
$criteria->group = 't.order_product_id, t.type';

这有以下 SQL 查询 -

SELECT COALESCE (oca.reason, ocd.reason) AS reward, SUM(t.points) AS points, COUNT(t.redeemed_code_id) AS totalCount
FROM
`organisation_classroom_redeemed_codes` `t`
  LEFT JOIN organisation_classroom_deductions ocd ON ocd.deduction_id = t.order_product_i AND t.type = 1 LEFT JOIN organisation_classroom_achievements oca ON oca.achievement_id = t.order_product_id AND t.type = 2 LEFT JOIN myuser ON (myuser.user_id = t.myuser_id)
  WHERE myuser.organisation_id = 37383
  GROUP BY t.order_product_id, t.type

此查询在 运行 直接在数据库中工作正常并且 returns 预期数据。然而,问题是当我 运行 将标准逻辑放入我的 CAtiveDataProvider() 时,我得到了错误。

    return new CActiveDataProvider($this, array(
        'criteria' => $criteria
    ));

任何人都可以建议如何解决此问题以使其与我的 CActiveDataProvider 一起工作吗?

按如下方式指定您的select:

$criteria->select = array(
    'COALESCE(oca.reason, ocd.reason) AS reward_name',
    'SUM(t.points) AS points',
    'COUNT(t.redeemed_code_id) AS totalCount'
);

您的代码失败的原因是在 CActiveFinder 的第 917 行(至少在我使用的 Yii 1.14 中)使用以下逻辑来处理字符串 select 语句:

if(is_string($select))
    $select=explode(',',$select);

你的 select 语句中的 explode 惨遭失败,因为你在表达式中有逗号。将您的 select 格式化为数组,如上所示,以避免此问题。