我在 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());
}