CakePHP - 创建子查询

时间:2015-01-06 10:34:05

标签: cakephp subquery cakephp-3.0 nested-query

我用过的CakePHP版本是3.x. 我需要cakePHP来创建这个sql语句:

    SELECT messages.id, message, receiver_id, sender_id, conversation_id, users.id, users.username FROM 
(
    SELECT messages.id, message, receiver_id, sender_id, conversation_id
    FROM messages as messages
    ORDER BY created DESC
) AS messages
left join users on (users.id = sender_id)
WHERE (sender_id = 13 or receiver_id =13)
GROUP BY conversation_id; 

我使用了queryBuilder,但我真的不明白我在做什么;)

这是我的蛋糕代码:

$subquery = $messages->find()
        ->order(['Messages.created' => 'DESC']);
    debug($neededMessages = $messages->find('all')
        ->select()
        ->group('Messages.conversation_id')
        ->contain(['Users'])
        ->where(['OR' => ['sender_id' => $userId, ['receiver_id' => $userId]]]));
    $neededMessages->execute();

我觉得那里只有一点点错误。 蛋糕调试输出是这样的: SELECT(SELECT Messages.id AS Messages__id,Messages.subject AS Messages__subject,Messages.message AS Messages__message,Messages.created AS Messages__created,Messages.conversation_id AS {{1 },Messages.is_new AS Messages__conversation_id,Messages.receiver_id AS Messages__is_new,Messages.sender_id AS Messages__receiver_id FROM messages消息ORDER BY Messages.created DESC)FROM messages消息INNER JOIN users Users ON Users.id =(Messages.sender_id)WHERE(sender_id =:c0 OR receiver_id =:c1)GROUP BY Messages.conversation_id

我错过了第一个select语句中的列。 有人可以帮忙解决这个问题吗? grretings maik ...

2 个答案:

答案 0 :(得分:0)

所以,我的结果是我需要的。 唯一困扰我的是我现在有阵列而没有对象。这是我的代码:

$conn = ConnectionManager::get('default'); $stmt = $conn->query('SELECT max(m.id) as message_id, message, receiver_id, sender_id, m.conversation_id, users.id as user_id, users.username from (select id, message, receiver_id, sender_id, conversation_id from messages order by created desc) as m left join users as users on (m.sender_id = users.id) group by m.conversation_id'); $messages = $stmt->fetchAll('assoc'); $this->set('messages', $messages);

很高兴从其他蛋糕用户那里了解他们如何解决这个问题' ...

答案 1 :(得分:-1)

为什么不将它作为SQL命令手动编写?我不认为CakePHP支持嵌套查询。

$this->Model->query($query_string);