I have a typical hasMany method:
public function earmarks() {
return $this->hasMany('App\Earmark');
}
But how do I add a join and some other conditions to this relationship when I use the ->with('earmarks')
to retrieve them? I want to add:
->join('locations', 'locations.id', '=', 'earmarks.location')
->select('earmarks.*', 'locations.location AS em_location')
->orderBy('date', 'asc');
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With