Chaining eager loading

Submitted by milon - 9 years ago

You can chain eager loading to avoid N+1 problem. Suppose you have 3 tables. customer[id, email], pos[id, serial_number] and restaurant[id, name, customer_id, pos_id] so restaurant table can act like a pivot table and it also have some value attribute. So now we can call customer from pos table via chaining eager loading.

/**
 *  Relationships
 */

#Customer model
public function restaurant(){
    return $this -> hasOne('Restaurant');
}

#Pos model
public function restaurant(){
    return $this -> hasOne('Restaurant');
}

#Restaurant model
public function customer(){
    return $this->belongsTo('Customer');
}

public function inventory(){
    return $this->belongsTo('Pos');
}

/**
 *  Eagerloading(probably on controller)
 */

$pos_list = Pos::with(['restaurant', 'restaurant.customer'])->get();
dd($pos_list);