如何通过"获得"订单的所有用户与CakePHP的HABTM关系的最新帖子

时间:2012-06-15 11:59:40

标签: cakephp cakephp-1.3

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

1 个答案:

答案 0 :(得分:0)

您可以在paginate options数组中指定连接,就像在find选项中一样:

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