Eloquent - how to add a join in the hasMany relationship?
OK, figured out I need a closure in my with()
clause, like this:
$updated_laptops = Laptop::with([
'earmarks' => function($q) {
$q
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc');
}
])->addJoins()->selectListCols()->find($request->IDs)->keyBy('id');
this worked for me
public function earmarks() {
return $this->hasMany('App\Earmark', 'labtop_id', 'id')
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc')->get();
}
it can be a attribute in Labtop Model and be serializable in Labtop json object like this :
public function GetEarmarksAttribute() {
return $this->hasMany('App\Earmark', 'labtop_id', 'id')
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc')->get();
}
protected $appends = array('earmarks');