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


i trying add 2 different search variations project. there model "user" , model "tag". user has many tags. want able search users specific tags. either want show users has of specified tags. got working way:

$query = $this->users->find(); $query->matching('tags', function ($q) {     return $q->where(['tags.name' => 'tag1'])              ->orwhere(['tags.name' => 'tag2']); }); 

but want find users have both tags @ same time. tried ->andwhere instead of ->orwhere, result empty.

how can find users contain multiple tags?

thanks

there few ways achieve this, 1 group results , use having compare count of 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 select users have 2 distinct tags, can tag1 , tag2 since these ones being joined in. in case name column unique, may count on primary key instead.

the in btw. same or conditions (the database system expand in or conditions accordingly).


Comments

Popular posts from this blog

twig - Using Twigbridge in a Laravel 5.1 Package -

jdbc - Not able to establish database connection in eclipse -

Kivy: Swiping (Carousel & ScreenManager) -