我有一个文章表和一个评论表。文章有很多评论。每条评论属于评论状态(comment_status_id):1。好,或2.差,或3.丑。
我想查询所有只有状态为3的评论文章(丑陋)。也就是说,排除具有状态1或2的任何评论的文章。
我可以编写一个子查询和查询来获取所有带有状态丑陋评论的文章:
$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的评论。
所以我的问题是:是否有一种有效/优雅的方法使查询与查询生成器一起工作,因此结果只是具有全部注释的文章为comment_status 3(丑陋)?
我确定我可以使用for循环解析$ query结果并构建一个新的结果数组,但我想看看是否有更好的方法在初始查询和/或/子查询中执行此操作。提前感谢任何建议!
D.
遵循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.
来自Cake Book - Retrieving Data & Results Sets
$articles = $this->Articles
->find()
->contain(['Comments'])
->notMatching('Comments.CommentStatus', function($q) {
return $q->where(['CommentStatus.comment_status_id' => '3'];
});