[英]Get Model by relationship ID's
I have an Accomodation
and a Feature
Model. 我有一个
Accomodation
和一个Feature
模型。 An accomodation can have many features (kitchen, balcony, etc.) via accomodation_feature
pivot table: 通过
accomodation_feature
数据透视表,住宿可以具有许多功能(厨房,阳台等):
//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()
方法的额外参数:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.