cakephp - 如何在 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.
解决方案
按照 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.
推荐阅读
- html - 将 div 居中在 2 个 div 上的 CSS 指南
- python - python instance() 或 type() 无法得到正确的结果
- ios - 删除 UIBezierPath 上的额外空间
- angular - 错误 无法加载 PDF 文档。(角5)
- java - 代码给出 -1 而不是 4。方法应该返回一个值
- c# - 以编程方式合并几何,同时保持每个形状的单独位置?
- javascript - 如何从json打印精确的html标签
- java - 哪一个更好地传递给 StringBuilder.append?
- android - 我想将 imageview 标签与 imageview backgroundresource 进行比较?
- django - Django Form 转换为 Django Rest Framework Serializer