Yii 1.1模型关系不能在选择时使用联接表列

时间:2019-01-13 04:24:46

标签: mysql yii

这是我的课程

Class System extends CActiveRecord
{
    public function relations() {
        return array(
            'SystemInverterModuleMountGrouped' => array(self::HAS_MANY, 'SystemInverterModule', array('id' => 'system_inverter_id'),
                'through' => 'SystemInverter',
                'group' => 'system_id, SystemInverterModuleMountGrouped.mount_id',
                'condition' => 'SystemInverterModuleMountGrouped.mount_id is not null AND SystemInverterModuleMountGrouped.mount_id != "" AND number_of_mounts > 0 AND
                    CASE WHEN Mount.unit_of_measure = 1 THEN
                        SystemInverterModuleMountGrouped.existing_array != 1
                    ELSE true
                    END',
                'select' => '*, '
                    . 'SUM(SystemInverterModuleMountGrouped.number_of_mounts) AS number_of_mounts_grouped, ', 
                'with' => 'Mount'
            )
        );
    }
}

这工作正常,但现在我想在一定条件下求和数

array(
    'select' => '*, '
        . 'IF(Mount.unit_of_measure IN (1,2,3), 0, SUM(SystemInverterModuleMountGrouped.number_of_mounts)) AS number_of_mounts_grouped, ',
)

它不起作用并且yii抛出错误

  

活动记录“ SystemInverterModule”正试图选择无效的列“ IF(Mount.unit_of_measure IN(1)。请注意,该列必须存在于表中或为具有别名的表达式。

请注意,我可以在条件下使用Mount.unit_of_measure

  

'condition'=>'当Mount.unit_of_measure = 1 THEN时的情况'

它适用于原始sql查询

SELECT IF(Mount.unit_of_measure IN (1,2,3), 0, SUM(SystemInverterModuleMountGrouped.number_of_mounts)) AS number_of_mounts_grouped
FROM `SystemInverterModules` `SystemInverterModuleMountGrouped`
LEFT OUTER JOIN `SystemInverter` `SystemInverter`
       ON (`SystemInverter`.`id` = `SystemInverterModuleMountGrouped`.`system_inverter_id`)
LEFT OUTER JOIN `Inventory` `Mount` 
       ON (`SystemInverterModuleMountGrouped`.`mount_id` = `Mount`.`id`)
WHERE (SystemInverterModuleMountGrouped.mount_id is not null AND SystemInverterModuleMountGrouped.mount_id != "" AND
       number_of_mounts > 0 AND
       CASE WHEN Mount.unit_of_measure = 1 THEN 
              SystemInverterModuleMountGrouped.existing_array != 1 
       ELSE true END
    )
    AND (`SystemInverter`.`system_id` = '42146')
GROUP BY system_id, SystemInverterModuleMountGrouped.mount_id
ORDER BY sort_mounting ASC

1 个答案:

答案 0 :(得分:1)

在这种情况下,应使用数组声明select-字符串格式不适用于复杂的表达式:

'select' => [
    '*',
    'IF(Mount.unit_of_measure IN (1,2,3), 0, SUM(SystemInverterModuleMountGrouped.number_of_mounts)) AS number_of_mounts_grouped', 
],