Post モデルと User モデルの間に HABTM 関係があります。
ここで、Post.published によって注文されたすべてのユーザーを受け取りたいと考えています。
このようなもの:
...
var $paginate = array(
'limit' => 8,
'recursive' => 1,
'fields' => array('id', 'username', 'image')
);
function index() {
$this->paginate['conditions'] = array('User.state'=>true);
$this->paginate['order'] = 'Post.published DESC';
$this->set('authors', $this->paginate());
}
...
これどうやってするの?出来ますか?
MySQL の場合:
SELECT users.id, users.username, users.image, posts.published FROM users INNER JOIN posts_users ON users.id = posts_users.user_id
INNER JOIN posts ON posts.id = posts_users.post_id
ORDER BY posts.published DESC;
ソリューション:
function index() {
$this->paginate['joins'] = array(
array('table' => 'posts_users', 'alias' => 'PostsUser', 'type' => 'inner', 'conditions'=>array('User.id = PostsUser.user_id')),
array('table' => 'posts', 'alias' => 'Post', 'type' => 'inner', 'conditions'=>array('Post.id = PostsUser.post_id'))
);
$this->paginate['fields'] = array('id', 'username', 'image');
$this->paginate['conditions'] = array('User.state'=>true);
$this->paginate['order'] = 'Post.published DESC';
$this->paginate['group'] = 'User.id';
$this->set('authors', $this->paginate());
}