1

我有多个这样的habtm:

// 用户模型
var $hasMany = array('Post');

// 发布模型
var $hasAndBelongsToMany = array('Category', 'Tag');

// 类别模型
var $hasAndBelongsToMany = array('Post');

// 标签模型
var $hasAndBelongsToMany = array('Post');

我试图获取所有帖子及其用户和标签(在某个类别中),不知何故,如果我获取标签,结果是错误的。

$this->paginate = array
(
    'Post' => array
    (
        'limit' => 2,

        'fields' => array(
            'Post.title', 'Post.content', 'Post.slug', 'Post.created',
            'Tag.name',
            'User.username', 'User.created', 'User.post_count', 'User.avatar_file_name'),

        'joins' => array
        (
            array(
                'table' => 'categories_posts',
                'alias' => 'CategoriesPost',
                'type' => 'inner',
                'conditions'=> array('CategoriesPost.post_id = Post.id')
            ),

            // FETCH USER
            array(
                'table' => 'users',
                'alias' => 'User',
                'type' => 'inner',
                'conditions'=> array('Post.user_id = User.id')
            ),

            // FETCH TAGS
            array(
                'table' => 'posts_tags',
                'alias' => 'PostsTag',
                'type' => 'inner',
                'conditions'=> array('PostsTag.post_id = Post.id')
            ),

            array(
                'table' => 'tags',
                'alias' => 'Tag',
                'type' => 'inner',
                'conditions'=> array('Tag.id = PostsTag.tag_id')
            ),

            array(
                'table' => 'categories',
                'alias' => 'Category',
                'type' => 'inner',
                'conditions'=> array('Category.id = CategoriesPost.category_id', 'Category.slug' => $slug)
            )
        )
    )
);

$posts = $this->paginate();

既然我是新手,谁能给我一个解决方案?非常感谢...

4

1 回答 1

1

在尝试使用关联模型对结果集进行分页时,我遇到了类似的问题。我最终不得不手动将我的模型绑定在一起,运行查询,然后解除绑定,以便让 Cake 包含正确的数据。(http://book.cakephp.org/view/86/Creating-and-Destroying-Associations-on-the-Fly

您还可以尝试可包含的行为,这将允许您指定要包含在结果集中的模型。Containable 是 1.2+ ( http://book.cakephp.org/view/474/Containable ) 的核心,否则您需要自己获取它。

不过,我不太确定您为什么在那里有如此庞大的查询。我会更倾向于做类似以下的事情。

$this->Model->recursive = 2;
$this->Model->paginate();

并让 Cake 通过我的关联为我获取所有相关数据。然后我会使用条件数组(http://api.cakephp.org/class/controller#method-Controllerpaginate)调整返回来指定类别。

抱歉,这不是一个事实上的解决方案,但我自己是个 CakePHP 爱好者!您可能会发现使用 DebugKit 更容易查看查询、结果等, http: //github.com/cakephp/debug_kit

于 2010-03-16T10:49:06.767 回答