简体   繁体   中英

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.

Use the extra parameters of the whereHas() method:

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

ie:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM