Tago
Tago

Reputation: 31

How to Make Laravel Eloquent with (hasMany) and whereIn Query?

I want to make query in Laravel Eloquent like here its.

In have two Models File and Tags. File has an relationship to Tags - has Many

class File extends Model
  ....
   public function tags()
   {
      return $this->hasMany('App\Models\Tags');
   }
 .....
}

Every File has many Tags and in need the File which have all of the tags.

For example:

File 1 has Tag 1,2,3

File 2 has Tag 2,3

When i search for Tag 2, get File 2, when i search for Tag 1 and 2 i would like to have only File 1 with has both tags.

The funktions i have tried

   $files = File::with(['tags' => function ($query){
        $query->whereIn('tag_id', array(1,2)); 
    }])->get();

   $files = File::whereHas('tags', function ($query) {
            $query->whereIn('tag_id', [1,2]);
        })->get();

But i get File 1 und 2, i only need File 1 with TAG 1und2

Upvotes: 1

Views: 1617

Answers (2)

Tago
Tago

Reputation: 31

i have found a solution

   $q = File::with('tags');
    foreach ($tag_ids as $tag_id) {
        $q->whereHas('tags', function ($query) use ($tag_id){
            $query->where('tag_id', '=', $tag_id);
        });
    }
    $files = $q->get(); 

Upvotes: 0

Sohel0415
Sohel0415

Reputation: 9853

Change your code like below-

 $tag_ids=[1,2];
 $files = File::whereHas('tags', function ($query) use ($tag_ids){
       foreach($tag_ids as $tag_id){
        $query->where('tag_id', '=',$tag_id);
       }
    })->with('tags')->get();

This will act like a and query through your tag_ids.

Upvotes: 1

Related Questions