1

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

1 回答 1

0

您可以在分页选项数组中指定连接,就像在查找选项中一样:

class PostsController extends AppController {

    public function by_tag ( $tag ) {
        /**
          * This will fetch Posts tagged $tag (say, 'PHP')
          */


        $this->paginate['Post'] = array(
            'limit' => 10,
            'contain' => '',
            'conditions' => array(
                'Post.published' => 1
            ),
            'fields' => array('Post.*', 'Tag.*'),
            'joins' => array(
                array(
                    'table' => 'posts_tags',
                    'type' => 'INNER',
                    'alias' => 'PostTag',
                    'conditions' => array(
                        'Post.id = PostTag.post_id'
                    )
                ),
                array(
                    'table' => 'tags',
                    'alias' => 'Tag',
                    'type' => 'INNER',
                    'conditions' => array(
                        "PostTag.tag_id = Tag.id AND Tag.name = '$tag'"
                    )
                )
            )
        );

        $data = $this->paginate('Post');
        $this->set(compact('data'));
    }
}

http://planetcakephp.org/aggregator/items/3544-using-mysql-inner-join-in-cakephp-pagination

于 2012-06-17T11:14:26.633 回答