Vinod VT
Vinod VT

Reputation: 7164

How to write join queries in CakePHP?

I have two tables posts and users. The post.user_id=users.id.

The fields are

user: id, username, password
post: id, user_id, post_name

I would like to select post.id, post.post_name, user.username.

How to select this in CakePHP?

I have two Models named User and Post. It calls the Model from PostController.

Upvotes: 0

Views: 133

Answers (2)

Chris
Chris

Reputation: 429

You should properly define the relations between the two models in order to simplify your life, but if you want to use a join, here is the syntax:

find('all', array(
        'conditions' => array('name' => 'Thomas Anderson'),
        'joins' => array(
            array(
                'alias' => 'Thought',
                'table' => 'thoughts',
                'type' => 'LEFT',
                'conditions' => '`Thought`.`person_id` = `Person`.`id`'
            )
        )
 ));

Upvotes: 2

toby1kenobi
toby1kenobi

Reputation: 1691

If you have correctly defined the relationship between those two models, this should just happen when you use the Post model's find method:

// In PostsController
$posts = $this->Post->find('all');

// $posts should be an array like this
Array
(
    [0] => Array
        (
            [Post] => Array
                (
                    // Model data
                )
            [User] => Array
                (
                    // Model data
                )
        )
)

Hope this helps.

Upvotes: 3

Related Questions