Search code examples
phplaraveleloquentmany-to-manyrelationship

Laravel many to many relation search


I have three models right now

User

public function languages(){
    return $this->belongsToMany('App\Language');
}

Newspaper

public function languages(){
    return $this->belongsToMany('App\Language');
}

Language

public function users(){
    return $this->belongsToMany('App\User');
}

public function newspapers(){
    return $this->belongsToMany('App\Newspaper');
}

I have already have the language_user, language_newspaper table

And in tinker, I have successfully retrieve both relation by attach() blablabla.

The question is How could I search for Newspaper that User id1 has this Language in eloquent? It seems quite complicated for me.

User id1 -> has language en, zh

Newspaper id1 -> has language en, jp ->OK

Newspaper id2 -> has language zh ->NOT OK

I have tried this but not sure if it is correct or not

$where = [];

foreach ($agent->languages as $language) {
array_push($where, $language->id);}

$newspapers = Newspaper::
join('language_newspaper', function ($join) use ($where) {
    $join->on('newspaper.id', '=', 
        'langauge_newspaper.newspaper_id')
        ->whereIn('langauge_newspaper.newspaper_id', $where);
})
->groupBy('newspaper.id')
->get();

Solution

  • You should be able to use whereHas in this scenario, like this:

    $newspapers = Newspaper::whereHas('languages', function ($q) use ($agent) {
                     $q->whereIn('id', $agent->languages->lists('id)->all());
                  })->get();