2

如何以 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声明,请帮助我..

4

2 回答 2

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
);
于 2013-05-07T06:38:34.113 回答
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
于 2013-05-07T06:21:53.133 回答