Question: How to have multiple layers of hasMany() relation for Laravel 5?

Question

How to have multiple layers of hasMany() relation for Laravel 5?

Answers 1
Added at 2016-12-28 05:12
Tags
Question

Let say I have tables like the following:

order
 order_id | customer_name | delivery_address        
 1        | David         | ABC Road, DEF district 
...........Some other record ..............

order_dish
order_id | dish_id | dish_name
1        | 1       | chicken wing
1        | 2       | meat pie
1        | 3       | onion ring
...........Some other record ..............

dish_ingredient
dish_id | ingredient
1       | chicken wing
1       | salt
1       | oil
2       | pork meat
2       | flour
3       | onion
...........Some other record ..............

In Laravel 5, if I want to get all dishes of an order, I can do:

$order = Order::hasMany('App\OrderDish', 'order_id')->get();

Is there a way I can get all ingredients needed for an order in one line?

Answers
nr: #1 dodano: 2016-12-28 10:12

Yes. The "has-many-through" relationship provides a convenient shortcut for accessing distant relations via an intermediate relation. You define it using hasManyThrough() method of your model.

First, define the relation in your Order model:

class Order extends Model {
  public function ingredients() {
    return $this->hasManyThrough('App\DishIngredient', 'App\OrderDish', 'order_id', 'dish_id');
  }
}

With such a relation defined, you'll be able to get ingredients for given order with:

$ingredients = $order->ingredients;
Source Show
◀ Wstecz