【问题标题】:JOIN in CakePHP - A better understandingJOIN in CakePHP - 更好的理解
【发布时间】:2015-01-17 12:15:06
【问题描述】:

我想通过解决以下示例更好地理解 CakePHP (v 2.4.5) 中的 joins

Post hasMany Comment
Post.id == Comment.post_id
Comment.published 可以是10

  • 我需要查找至少有一条已发表评论的所有帖子
  • 我想编写来自Post 模型的查询。为了不破坏分页,所以我可以添加基于Post 的顺序/条件
  • 我不想在 PHP 中过滤掉结果(为了不破坏分页)

您可能会建议从Comment 模型中解决此问题,如下所示:
https://stackoverflow.com/a/3890461/155638
但这是为了更好地理解连接,所以我想设置一个要求来编写来自 Post 模型的查询。

我大致有以下想法,希望RIGHT join能排除所有不符合条件的帖子:

$this->Post->find('all', array(
    'joins' => array(
        array(
            'table' => 'comments',
            'alias' => 'CommentsJoined',
            'type' => 'RIGHT',
            'conditions' => array(
                'Post.id = CommentsJoined.post_id',
                'CommentsJoined.published = true'
            )
        )
    ),
    'contain' => array(
        'Comment' => array(
             'conditions' => array(
                 'Comment.published' => 1
             )
        )
    )
);

但它还没有为我工作。
目前,我的查询返回 19 次相同的帖子,而不是 19 个不同的帖子。

从这里怎么走?方法正确吗?

亲切的问候!
巴特

【问题讨论】:

    标签: cakephp join pagination


    【解决方案1】:

    看来我是在正确的轨道上。最后一步是删除重复的帖子。
    这是通过将'group' => 'Post.id' 作为属性添加到查询来完成的。

    像这样:

    $this->Post->find('all', array(
        'joins' => array(
            array(
                'table' => 'comments',
                'alias' => 'CommentsJoined',
                'type' => 'RIGHT',
                'conditions' => array(
                    'Post.id = CommentsJoined.post_id',
                    'CommentsJoined.published = true'
                )
            )
        ),
        'group' => 'Post.id',
        'contain' => array(
            'Comment' => array(
                 'conditions' => array(
                     'Comment.published' => 1
                 )
            )
        )
    );
    

    【讨论】:

      猜你喜欢
      • 2015-12-04
      • 2019-04-10
      • 2016-04-09
      • 2018-11-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      相关资源
      最近更新 更多