在cakephp的查询中使用case

时间:2013-05-07 05:29:00

标签: cakephp

如何以cakephp格式编写以下sql查询

SELECT 
`ActivityLog`.`id`, 
CASE User.user_type
WHEN 'admin' THEN concat_ws(' ',Admin.first_name,Admin.last_name)
END,
FROM `project`.`activity_logs` AS `ActivityLog` 
left join users as User on ActivityLog.user_id = User.id 
left join admins as Admin on User.id = Admin.user_id
WHERE 1 = 1 ORDER BY `ActivityLog`.`datetime` desc

一切都很好,除了case声明,请帮助我..

2 个答案:

答案 0 :(得分:4)

尝试此查询

$this->ActivityLog->find('all', array(
  'fields' => array(
       'ActivityLog.id',
       '((CASE User.user_type WHEN 'admin' THEN concat_ws(' ',Admin.first_name,Admin.last_name) END)) AS UserName'
   ),
   'joins' => array(
        'LEFT JOIN users as User ON ActivityLog.user_id = User.id'
        'LEFT JOIN admins as Admin on User.id = Admin.user_id'
    ),
   'recursive' => -1
);

答案 1 :(得分:1)

你可以在cakePHP中使用CASE,

$this->YourModel->find('all', array(
  'fields' => array(
    'ActivityLog.id',
    '((CASE User.user_type WHEN 'admin' THEN concat_ws(' ',Admin.first_name,Admin.last_name)
END)) AS
some_alias_name'
  ) 
....rest of your query