Adrenaxus
Adrenaxus

Reputation: 1613

Get Model by relationship ID's

I have an Accomodation and a Feature Model. An accomodation can have many features (kitchen, balcony, etc.) via accomodation_feature pivot table:

//accomodation model
public function features()
{      
    return $this->belongsToMany('Feature');
}

I want to select ALL accomodations that have ALL selected features activated. For example I want all accomodations that have a balcony AND a kitchen AND a microwave oven.

I tried the following but I get every accomodation that has a balcony OR a kitchen OR a microwave oven:

$features = array("1", "2", "3"); //id's of the features I want to select

$accomodations = Accomodation
::whereHas('features', function($q) use ($features)
                {
                    $q->whereIn('features.id', $features);
                })                                
->get();

How can I select all accomodations that have ALL of the provided features?

Thanks in advance for any help, and sorry for the (maybe) misleading title. I couldn't think of anything more appropriate.

Upvotes: 0

Views: 46

Answers (2)

cre8
cre8

Reputation: 13562

Wherein is definitely wrong. Try to loop through your features:

for each($features as feature)
    $q->where('features.id', feature);

Upvotes: 0

Javi Stolz
Javi Stolz

Reputation: 4755

Use the extra parameters of the whereHas() method:

whereHas($relation, Closure $callback, $operator = '>=', $count = 1)

i.e:

Accomodation::whereHas('features', function($q) use ($features) {
    $q->whereIn('features.id', $features);
}, '>=', count($features))->get();

Upvotes: 1

Related Questions