我正在修复一个项目,并在模型中创建了一个范围以查询关系,该关系也执行了闭包操作:
这是范围,这是一家酒店:
public function scopeIsHotelAvailable($query, $start_date, $end_date){
return $query->whereHas('isAvailableInRanges', function($q) use ($start_date, $end_date) {
$q->isAvailableInRanges($start_date, $end_date);
});
}
当我什至尝试运行此命令时,都会出现以下错误:
$hotel->ishotelavailable($start, $end);
TypeError: Too few arguments to function Modules/Hotel/Models/Hotel::isAvailableInRanges(), 0 passed in /home/ffuentes/pk2/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Concerns/QueriesRelationships.php on line 475 and exactly 2 expected
我以前见过这个,但是我不知道如何使Eloquent识别这些论点。
编辑:
这是从酒店模型的闭包中调用的方法。
public function isAvailableInRanges($start_date,$end_date){
$days = max(1,floor((strtotime($end_date) - strtotime($start_date)) / DAY_IN_SECONDS));
if($this->default_state)
{
$notAvailableDates = $this->hotelDateClass::query()->where([
['start_date','>=',$start_date],
['end_date','<=',$end_date],
['active','0']
])->count('id');
if($notAvailableDates) return false;
}else{
$availableDates = $this->hotelDateClass::query()->where([
['start_date','>=',$start_date],
['end_date','<=',$end_date],
['active','=',1]
])->count('id');
if($availableDates <= $days) return false;
}
// Check Order
$bookingInRanges = $this->bookingClass::getAcceptedBookingQuery($this->id,$this->type)->where([
['end_date','>=',$start_date],
['start_date','<=',$end_date],
])->count('id');
if($bookingInRanges){
return false;
}
return true;
}
所有这些的目的是针对这些结果测试查询结果并对其进行过滤。那时,当我开始尝试时,我只是过滤了集合,但由于返回的集合不包含分页和通常包含在自身中的雄辩元素,因此无法正常工作。
答案 0 :(得分:0)
您使用的是作用域方法而不是关系,请尝试在whereHas中使用关系方法,例如:
->whereHas('yourRelationshipMethod', function($q) {...});
isAvailableInRanges
在酒店模型中,因此您可以按酒店而不是关系模型来调用它。
但是isAvailableInRanges
是一个实例方法,因此您不能仅由Eloquent构建器调用它,您需要获取实例并调用此方法:
Hotel::first()->isAvailableInRanges($start_date,$end_date);