I defined a relation like this on my model class
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'
)
);
}
}
This is working fine, but now I want to sum number_of_mounts in a certain condition
array(
'select' => '*, '
. 'IF(Mount.unit_of_measure IN (1,2,3), 0, SUM(SystemInverterModuleMountGrouped.number_of_mounts)) AS number_of_mounts_grouped, ',
)
It doesnât work and yii throws an error
Active record âSystemInverterModuleâ is trying to select an invalid column âIF(Mount.unit_of_measure IN (1â. Note, the column must exist in the table or be an expression with alias.
Notice that Iâm able to use Mount.unit_of_measure
on the condition
âconditionâ => 'CASE WHEN Mount.unit_of_measure = 1 THEN â
And when I try to write raw sql query, it also work
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