使用Yii2 ActiveRecord在SELECT中具有大小写的子查询

时间:2019-11-23 11:18:45

标签: yii2

是否可以在Yii2中将这种SQL转换为ActiveRecord查询:

SELECT a.id, 
    case length(a.id)
            when 6 then (select region_name from region where id = concat(left(a.id,2),'0000'))
            when 5 then (select region_name from region where id = concat(left(a.id,1),'0000'))
    end as prov,
    case length(a.id)
            when 6 then (select region_name from region where id = concat(left(a.id,4),'00'))
            when 5 then (select region_name from region where id = concat(left(a.id,3),'00'))
    end as kab,
   (select region_name from region where id = a.id) as kec
FROM region as a 
WHERE a.region_name LIKE '%kamb%'

1 个答案:

答案 0 :(得分:0)

绝对将其转换为查询版本

$query = new \yii\db\Query;
$query->from("region as a ");
$query->select(new \yii\db\Expression("a.id, 
    case length(a.id)
            when 6 then (select region_name from region where id = concat(left(a.id,2),'0000'))
            when 5 then (select region_name from region where id = concat(left(a.id,1),'0000'))
    end as prov,
    case length(a.id)
            when 6 then (select region_name from region where id = concat(left(a.id,4),'00'))
            when 5 then (select region_name from region where id = concat(left(a.id,3),'00'))
    end as kab,
    (select region_name from region where id = a.id) as kec"));
$query->andWhere(['like', 'a.region_name', 'kamb']);
echo $query->createCommand()->rawSql;

对于 ActiveRecord查询,请替换上面的选择部分