Laravel tag search to return images that contain all tags

前端 未结 2 1928
萌比男神i
萌比男神i 2021-01-03 12:09

I\'m developing an application that lists images, and has multiple tags assigned to each image. I\'d like to be able to find the images that are tagged with all

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-03 12:41

    Manual count and having would work, but you can use simple whereHas instead:

    // let it be array of tag ids:
    $tagsIds;
    
    $images = Image::whereHas('tags', function ($q) use ($tagsIds) {
       $q->whereIn('tags.id', $tagsIds);
    }, '=', count($tagsIds))->get();
    

    However mind that both mine and @user3158900's solutions will work only, when you have no duplicates on the pivot table. Using Eloquent's attach method on BelongsToMany relation may lead to such situation.

提交回复
热议问题