failedCoder
failedCoder

Reputation: 1424

Laravel whereIn() acting like orWhereIn()

There are 3 tables:

  1. meals
  2. tags
  3. meal_tag

I want to get all meals that have all of the tags from an url query.

For example: .../api/query?tags=1,2,3

In this example I want to fetch all meals that have

tag1 AND tag2 AND tag3

,but my query returns meals that have

tag1 OR tag2 OR tag3

Here is my query:

   $query = Meal::query();  
   ...

   if ($request->has('tags')) {

        $inputTags = $request->query('tags');

        $tags = explode(',', $inputTags);


        $query = $query->whereHas('tags', function($q) use ($tags) {
            $q->whereIn('tags.id', $tags);
        });
    }

Upvotes: 1

Views: 1913

Answers (1)

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

IN() checks whether a value is within a set of values, for any value matched then return true, It doesn't verify for all values to be present,

To achieve for what you are trying you need to check each tag id individually using whereHas to make sure all of these are present

if ($request->has('tags')) {
    $inputTags = $request->query('tags');
    $tags = explode(',', $inputTags);
    foreach($tags as $tag){
        $query = $query->whereHas('tags', function($q) use ($tag) {
            $q->where('id','=', $tag);
        });
    }
}

Upvotes: 1

Related Questions