Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在CakePHP 3.x中基于单个值查询HasMany关联_Cakephp_Associations_Cakephp 3.x_Querying - Fatal编程技术网

如何在CakePHP 3.x中基于单个值查询HasMany关联

如何在CakePHP 3.x中基于单个值查询HasMany关联,cakephp,associations,cakephp-3.x,querying,Cakephp,Associations,Cakephp 3.x,Querying,我有一个文章表和评论表。 文章有很多评论。 每个注释都属于一个注释状态(注释状态id): 1.好,还是 2.坏的,或者 3.丑陋的 我想做一个查询,查找所有只有状态3(丑陋)注释的文章。也就是说,排除包含状态为1或2的任何注释的文章 我可以编写一个子查询和一个查询,以获取所有包含状态为“丑陋”的评论的文章: $matchingComments = $this->Articles->getAssociation('Comments')->find() ->selec

我有一个文章表和评论表。 文章有很多评论。 每个注释都属于一个注释状态(注释状态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的文章

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

我确信我可以用for循环解析$query结果并构建一个新的结果数组,但我想看看是否有更好的方法在初始查询和/或子查询中实现这一点。 提前感谢您的建议


D.

遵循ndm的建议,首先让原始sql工作,此查询适用于my matchingComments查询

SELECT `article_id`
FROM `comments`
GROUP BY `article_id`
HAVING MIN(`comment_status_id`) = 3
AND MAX(`comment_status_id`) = 3;
因此,在我的蛋糕控制器中,这起作用:

$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.

来自


您知道如何在原始SQL中执行此操作吗?最好先弄清楚。谢谢你。。。。是的,这是解决问题的正确方法。我将在下面添加我的解决方案。谢谢Dennis。这种方法会生成一个包含非状态3注释的所有文章的列表,并按注释列出它们,因此列表中会多次重复同一篇文章,而不是目标。不管怎样,我将尝试匹配和不匹配的组合,看看效果如何。谢谢。只需尝试将“notMatching”放在包含类似“Comments”=>静态函数($q)={return$q->notMatching….}的静态函数中;
$articles = $this->Articles
    ->find()
    ->contain(['Comments'])
    ->notMatching('Comments.CommentStatus', function($q) {
        return $q->where(['CommentStatus.comment_status_id' => '3'];
    });