0

I', learning CakePHP, but I have a great problem with operating with more complex database queries. So I would like to execute that kind of query:

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

Can anybody help me write this using cakePHP mechanism for preparing queries?

1
  • Are you trying to use the find() method on a Book model with this SQL statement?
    – AgRizzo
    Oct 8, 2013 at 10:57

3 Answers 3

3

Your code should be something similar to this, assuming Book e Project are in relationship (Book belongsTo 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'
    )
);
1
  • Great, I think this is something I was looking for :) Thx
    – bbbb
    Oct 8, 2013 at 13:08
0

Use IN clause.

   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
0

if Book and Projects are Models, you can use Book model to directly join using the CakePHP function, refer to https://stackoverflow.com/a/16286735/2858188

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.