duanmengmiezen8855 2015-06-19 12:43
浏览 6
已采纳

如何匹配与特定其他记录集关联的记录?

I am trying to add to two different search variations to my project. There is a model "User" and a model "Tag". A User has many Tags. Now I want to be able to search the Users with specific Tags. Either I want to show all Users that has any of the specified tags. I got this working this way:

$query = $this->Users->find();
$query->matching('Tags', function ($q) {
    return $q->where(['Tags.name' => 'Tag1'])
             ->orWhere(['Tags.name' => 'Tag2']);
});

But now I want to find all Users that have both Tags at the same time. I tried ->andWhere instead of ->orWhere, but the result is always empty.

How can I find Users that contain multiple Tags?

Thanks

  • 写回答

1条回答 默认 最新

  • dongzhang7157 2015-06-19 19:08
    关注

    There are a few ways to achieve this, one would be to group the results and use HAVING to compare the count of the distinct tags

    $query = $this->Users
        ->find()
        ->matching('Tags', function ($query) {
            return $query->where(['Tags.name IN' => ['Tag1', 'Tag2']]);
        })
        ->group('Users.id')
        ->having([
            $this->Users->query()->newExpr('COUNT(DISTINCT Tags.name) = 2')
        ]);
    

    This will select only those users that have two distinct tags, which can only be Tag1 and Tag2 since these are the only ones that are being joined in. In case the name column is unique, you may count on the primary key instead.

    The IN btw. is essentially the same as your OR conditions (the database system will expand IN to OR conditions accordingly).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题