Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Eloquent - how to add a join in the hasMany relationship?

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');
like image 942
daninthemix Avatar asked Nov 22 '16 18:11

daninthemix


Video Answer


2 Answers

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');
like image 74
daninthemix Avatar answered Oct 24 '22 04:10

daninthemix


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');
like image 42
Hamid Zandi Avatar answered Oct 24 '22 03:10

Hamid Zandi