Reputation: 445
I have two tables
posts
------
post_id | user_id | post_title | post_content
And
users
--------
id | user_name | user_ . .. . . . and so on
I need to fetch all posts with the user data to show the post writer etc..
How can I achieve this using CakePHP queries?
Upvotes: 0
Views: 102
Reputation: 114
$this->Post->find('all',array('fields'=>array('User.*'),'conditions'=>array('Post.user_id=User.id')),
joins' => array(
array(
'alias' => 'User',
'table' => 'users',
'type' => 'Inner',
'conditions' => array('User.user_id' =>$id)
)
)
));
Upvotes: 2
Reputation: 11302
In your UserModel you define:
var $hasMany = 'Post';
In your PostModel you define:
var $belongsTo = 'User';
Then you can get all post of some user doing:
$this->User->findAllById($id, array('recursive' => 2));
Or you can get ALL posts associated with the respective users doing:
$this->Post->find("all", array('recursive' => 2));
EDIT: Your Posts id column is named post_id so you must define primary key in your PostModel since CakePHP conventions is that primary key should be named id:
public $primaryKey = 'post_id';
Upvotes: 3