mercredi 4 juillet 2018

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);
        });
    }



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire