Richard Feliciano
Richard Feliciano

Reputation: 145

Querying many to many relation laravel

Im trying to query a many to many relationship with Laravel 5 eloquent,with a pivot table, im trying to retrieve only "articles" that has tag "A" and tag "B" together, but not succeed, eloquents bring articles that have tag "A" and tag"B", there`s any way to do this? nothing bellows it works.

$tags = [1,2,3];  
$result = Timetable::with([
    'tags' => function($query) use($tags){
        foreach($tags as $tag) {
            $query->where('id', $tag);
        }
    }
])->paginate();

$result = Timetable::with(['tags'])
                    ->whereHas('tags' => function($query) use($tags){
                            $query->whereIn('tag_id',$tags);
                    }
                )->paginate();

Upvotes: 0

Views: 109

Answers (1)

Javi Stolz
Javi Stolz

Reputation: 4755

Assuming you followed Laravel's naming rules for your relationships and foreign keys:

Get Timetables that have any of the tags

$result = Timetable::with('tags')->whereHas('tags', function($query) use ($tags) {
    $query->whereIn('tag_id', $tags);
})->paginate();

Get Timetables that have exactly all of the tags (no other tags accepted)

$result = Timetable::with('tags')->whereHas('tags', function($query) use ($tags) {
    $query->whereIn('tag_id', $tags);
}, '=', count($tags))->paginate();

Get Timetables that have all of the tags but they may also contain other tags

$result = Timetable::with('tags')->whereHas('tags', function($query) use ($tags) {
    $query->whereIn('tag_id', $tags);
}, '>=', count($tags))->paginate();

Same as above but excluding from the results the not matching tags

$result = Timetable::with(['tags' => function($query) use ($tags) {
    $query->whereIn('tag_id', $tags);
}])->whereHas('tags', function($query) use ($tags) {
    $query->whereIn('tag_id', $tags);
}, '>=', count($tags))->paginate();

Upvotes: 2

Related Questions