Yii Framework Forum

Can't select joined column in relations()


(Jackson Tong) #1

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

(Jackson Tong) #2

solved, I should use array in select instead of string
https://stackoverflow.com/a/54170514/3787302