M
M
Max2018-11-17 15:32:30
Laravel
Max, 2018-11-17 15:32:30

How to filter Products by all specified Tags for each of them?

There is a Product and Tags model. I linked them via belongsToMany.
How to filter Products by all specified Tags for each of them? i.e. for example, so that each product has tags 44,34,21,54 (not at least one of them, but all)

$tags_pages=[44,34,21,54]; // Это лишь пример массива. Элементы и количество  массива меняется.  

$Product = Product::whereHas('tags', function($query) use($tags_pages)
     {            
          $query->whereIn('id',$tags_pages);
      })->get();

This is how products are filtered if they have at least one specified tag. And it is necessary that all the specified tags be in each product.
Tried like this, but nothing output 0 products:
$tags_pages=[44,34,21,54];  // Это лишь пример массива. Элементы и количество  массива меняется.  
    $Product = Product::whereHas('tags', function($query) use($tags_pages)
         {    
               foreach($tags_pages as $tag){
                $query->whereIn('id', $tags_pages);
                }

          })->get();

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
Max, 2018-11-17
@jjsf

decision:

$tags_pages=[44,34,21,54]; // Это лишь пример массива. Элементы и количество  массива меняется.  

$Product = Product::whereHas('tags', function($query) use($tags_pages)
     {            
          $query->whereIn('id',$tags_pages);
      }, '=', count($tags_pages))->get();

i.e. we also check the number of tags

A
Arthur, 2018-11-17
@ART_CORP

It is necessary to read the documentation, everything is written there with an example.

You may also pass an array of conditions to the where function:

$users = DB::table('users')->where([
    ['status', '=', '1'],
    ['subscribed', '<>', '1'],
])->get();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question