How to match records that are associated with a specific set of other records?

前端 未结 1 2045
天涯浪人
天涯浪人 2020-12-22 09:58

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

相关标签:
1条回答
  • 2020-12-22 10:32

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

    0 讨论(0)
提交回复
热议问题