我有一个Accomodation
和Feature
模型。一个住宿可以有许多功能(厨房,阳台等)通过accomodation_feature
透视表:
//accomodation model
public function features()
{
return $this->belongsToMany('Feature');
}
我想选择所有住宿所有选中的功能激活。例如,我想要所有有阳台、厨房和微波炉的住宿。
我试过以下的住宿,但我得到了所有有阳台、厨房或微波炉的住宿:
$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();
如何选择具有所有所提供功能的所有住宿?
提前感谢任何帮助,并为(可能)误导性的标题感到抱歉。
使用whereHas()
方法的额外参数:
whereHas($relation, Closure $callback, $operator = '>=', $count = 1)
即:
Accomodation::whereHas('features', function($q) use ($features) {
$q->whereIn('features.id', $features);
}, '>=', count($features))->get();
其中肯定是错误的。尝试遍历你的特征:
for each($features as feature)
$q->where('features.id', feature);