Friday, March 31, 2017

Laravel hasMany with multiple constraints

I have query that I run on my ServiceController

return Service::with('contacts', 'locations.datetimes')->find($service->id);

This works great perfectly, but I need to change it. The relationships are defined as follows:

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');
  }
}

I need a second constraint on the datetimes where I need the relationship to be along the lines of

return $this->hasMany('App\Models\Service_detail')->where('service_id', $service->id);

The problem is I can't find a way to pass through the $service_id. How do you handle two constraints on a hasMany relationship?



via Craig Ward

Advertisement