0

我正在学习 CakePHP,但是在操作更复杂的数据库查询时遇到了很大的问题。所以我想执行那种查询:

SELECT p.name, b.value
FROM books b LEFT JOIN projects p
ON b.project_id=p.id
WHERE b.created=
(SELECT max(b.created) FROM books b WHERE b.user_id=1)
AND b.user_id=1
GROUP BY p.name

任何人都可以帮助我使用 cakePHP 机制来准备查询吗?

4

3 回答 3

3

您的代码应该与此类似,假设 Book e Project 有关系(BookbelongsTo Project

$this->Book->find
(
    'all',
    array
    (
        'fields' => array('Book.value', 'Project.name'),
        'conditions' => array
        (
            'Book.created IN (SELECT MAX(Book.created) FROM books Book WHERE Book.user_id = 1)',
            'Book.user_id' => 1
        ),
        'group' => 'Project.name'
    )
);
于 2013-10-08T11:05:42.127 回答
0

使用 IN 子句。

   SELECT p.name, b.value
   FROM books b 
   LEFT JOIN projects p ON b.project_id=p.id
   WHERE b.created IN (SELECT max(created) FROM books  WHERE user_id=1)
   AND b.user_id=1
   GROUP BY p.name
于 2013-10-08T10:51:07.213 回答
0

如果 Book 和 Projects 是 Models,可以使用 Book 模型直接使用 CakePHP 函数加入,参考https://stackoverflow.com/a/16286735/2858188

于 2013-10-08T11:23:26.070 回答