我查询我在ServiceController
return Service::with('contacts', 'locations.datetimes')->find($service->id);
这非常完美,但我需要改变它。关系定义如下:
class Service extends Model
{
public function locations()
{
return $this->belongsToMany('App\Models\Service_location', 'service_location_service');
}
}
class Service_location extends Model
{
public function datetimes()
{
return $this->hasMany('App\Models\Service_detail');
}
}
我需要对日期时间进行第二次约束,我需要将关系放在
行return $this->hasMany('App\Models\Service_detail')->where('service_id', $service->id);
问题是我找不到通过$ service_id的方法。你如何处理hasMany关系的两个约束?
答案 0 :(得分:1)
试试吧。将Service_location更改为此
class Service_location extends Model
{
public function datetimes()
{
return $this->hasMany('App\Models\Service_detail');
}
public function scopeServiceId($query)
{
return $query->where('service_id', $service->id);
}
}
现在您的查询将是
Service::with(['contacts', 'locations.datetimes' =>function($q) use($serviceId){
$q->serviceId($serviceId);
}])->find($service->id);
无法将参数传递给关系函数。如果您极有可能遇到N + 1查询问题。