小编典典

使用连接语句和子查询的CakePHP查询准备

sql

我正在学习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机制编写此语句来准备查询吗?


阅读 197

收藏
2021-05-16

共1个答案

小编典典

假设Book e Project处于关联关系(BookEmiratesTo 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'
    )
);
2021-05-16