eloquent - Nested Eager Loading with Joins in Laravel -
i have following tables , relationships
products table:
id product_name product_price 1 product 2 usd 2 product b 3 usd
components table
id component_name component_price 1 component 5 usd 2 component b 3 usd
product_component pivot table
id component_id product_id 1 1 1 2 1 2 3 2 2
orders table
id order_date 1 "2015-05-06"
order_items table
id order_id component_id quantity 1 1 1 1 2 1 2 2
the order model
class order extends model { public function items() { return $this->hasmany('orderitem'); } }
the orderitem model:
class orderitem extends model { public function orders() { return $this->belongsto('order'); } }
product model
class product extends model { public function components() { return $this->belongtomany('component'); } }
component model
class component extends model { public function products() { return $this->hasone('product'); } }
product component model
class productcomponent extends model { public function products() { return $this->belongsto('product')->withpivot(); } public function components() { return $this->belongsto('component')->withpivot(); } }
view
<h3>order id : {{ $order->id }} </h3> <h3>order date : {{ $order->order_date }} </h3> @foreach($order->items $item) <tr> <td>{{ $item->component_name }}</td> <td>{{ $item->component_price }}</td> </tr> @endforeach
my controller:
public function show($id) { $order = order::with(array('items' => function($query) { $query->join('components c', 'c.id', '=', 'order_items.component_id'); })) ->find($id); return view('orders', compact('order')); }
i able produce following report above code
order no : 1 order date : 2015-05-06 component 5 usd component b 3 usd
however, need order report in following format product details every product component.
order no : 1 order date : 2015-05-06 component - product 2 usd - product b 3 usd total 5 x 1 = 5 usd component b 3 usd - product b 3 usd total 3 x 2 = 6 usd
i think in correct direction, need guidance generate desired report.
you can eager-load nested relations follows:
order::with('items.products')->get();
Comments
Post a Comment