Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter model with HasMany relationship

Let's say I have two models: Park and Items. Each Park can have a number of Items, through a HasMany relationship.

In Items table there's a park_id field and a type flag: an Item can be a fountain, or a basketball court, or whatever.

What I need to do is to filter the parks to obtain only those who has ALL of the item types passed in an array. This is what I have:

$parks = Park::whereHas('items', function($q) use ($request) {
            $q->where('type', json_decode($request->type_list));
        })->get();

But it's not working properly. Any ideas?

Thanks a lot, and happy new year to all!

Edit: I've found a working though really ugly solution:

$types_array = json_decode($request->type_list, true);

$results = [];

// A collection of parks for each item type
foreach($types_array as $type) {
    $results[] = Park::whereHas('items', function($q) use ($type) {
        $q->where('type', $type);
    })->get();
}

// Intersect all collections
$parks = $results[0];
array_shift($results);

foreach ($results as $collection) {
    $parks = $collection->intersect($parks);
}

return $parks;
like image 839
Oscar Avatar asked May 02 '26 16:05

Oscar


1 Answers

You can use a foreach in whereHas method. It should be something like this:

$array = json_decode($request->type_list, true)
$parks = Park::whereHas('items', function($q) use ($array) {
             foreach ($array as $key => $type) {
                 $q->where('type', $type);
             }
         })->get();
like image 188
Laerte Avatar answered May 05 '26 02:05

Laerte



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!