Php 如何为Laravel 5创建多层hasMany()关系?
假设我有如下表格:Php 如何为Laravel 5创建多层hasMany()关系?,php,laravel,laravel-5,model,has-many,Php,Laravel,Laravel 5,Model,Has Many,假设我有如下表格: 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
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 ..............
在Laravel 5中,如果我想获得一份订单中的所有菜肴,我可以:
$order = Order::hasMany('App\OrderDish', 'order_id')->get();
有没有办法在一行中获得订单所需的所有配料?有。“有多个直通”关系为通过中间关系访问远程关系提供了方便的快捷方式。您可以使用模型的hasManyThrough()方法定义它
首先,在您的订单模型中定义关系:
class Order extends Model {
public function ingredients() {
return $this->hasManyThrough('App\DishIngredient', 'App\OrderDish', 'order_id', 'dish_id');
}
}
定义了这种关系后,您将能够通过以下方式获得给定订单的配料:
$ingredients = $order->ingredients;
检查,这将解决您的问题。您需要在订单模型中定义hasMany OrderDish。另外,orderDish模型应该有一个hasMany dishcomponents(如果我理解正确的话),你发布的代码不会让你得到“一份订单的所有菜肴”,因为你没有在任何地方传递订单ID