首页 > 解决方案 > 如何在 CakePHP 3.x 中基于单个值查询 HasMany 关联

问题描述

我有一个文章表和一个评论表。文章有很多评论。每个评论都属于一个评论状态 (comment_status_id):1. 好,或 2. 差,或 3. 丑。

我想查询所有只有状态为 3(丑陋)的评论的文章。也就是说,排除具有状态 1 或 2 的评论的文章。

我可以编写一个子查询和查询来获取所有带有 Status Ugly 评论的文章:

$matchingComments = $this->Articles->getAssociation('Comments')->find()
    ->select(['article_id'])
    ->distinct()
    ->where(['comment_status_id' => 3]);

$query = $this->Articles->find()
    ->where(['Articles.id IN' => $matchingComments]);

这给了我所有具有状态 3 的评论的文章。但它也包括状态为 2 或 1 的文章以及至少一个状态为 3 的评论。

所以我的问题是:有没有一种有效/优雅的方法可以使这个查询与查询生成器一起工作,所以结果只有评论都是评论状态为 3(丑陋)的文章?

我确定我可以使用 for 循环解析 $query 结果并构建一个新的结果数组,但我想看看在初始查询和/或/与子查询中是否有更好的方法来执行此操作。提前感谢您的任何建议!

D.

标签: cakephpassociationscakephp-3.xquerying

解决方案


按照 ndm 的建议首先让原始 sql 工作,此查询适用于我的 matchingComments 查询

SELECT `article_id`
FROM `comments`
GROUP BY `article_id`
HAVING MIN(`comment_status_id`) = 3
AND MAX(`comment_status_id`) = 3;

那么在我的 Cake 控制器中,这可以工作:

$matchingComments = $this->Articles->getAssociation('Comments')->find()
    ->select(['article_id'])
    ->group('article_id')
    ->having(['MIN(comment_status_id)' => 3])
    ->having(['MAX(comment_status_id)' => 3])

$query = $this->Articles->find()
    ->where(['Articles.id IN' => $matchingComments]);

不确定是否有更好的方法,但这很好用。再次感谢ndm。D.


推荐阅读