【发布时间】:2015-07-08 18:26:51
【问题描述】:
我有以下表格及其关系
产品表:
id product_name product_price
1 Product A 2 USD
2 Product B 3 USD
组件表
id component_name component_price
1 Component A 5 USD
2 Component B 3 USD
product_component 数据透视表
id component_id product_id
1 1 1
2 1 2
3 2 2
订单表
id order_date
1 "2015-05-06"
order_items 表
id order_id component_id quantity
1 1 1 1
2 1 2 2
订单模型
class Order extends Model {
public function items()
{
return $this->hasMany('OrderItem');
}
}
OrderItem 模型:
class OrderItem extends Model {
public function orders()
{
return $this->belongsTo('Order');
}
}
产品型号
class Product extends Model {
public function components()
{
return $this->belongToMany('Component');
}
}
组件模型
class Component extends Model {
public function products()
{
return $this->hasOne('Product');
}
}
产品组件模型
class ProductComponent extends Model {
public function products()
{
return $this->belongsTo('Product')->withPivot();
}
public function components()
{
return $this->belongsTo('Component')->withPivot();
}
}
查看
<h3>Order Id : {{ $order->id }} </h3>
<h3>Order Date : {{ $order->order_date }} </h3>
@foreach($order->items as $item)
<tr>
<td>{{ $item->component_name }}</td>
<td>{{ $item->component_price }}</td>
</tr>
@endforeach
我的控制器:
public function show($id)
{
$order = Order::with(array('items' => function($query)
{
$query->join('components AS c', 'c.id', '=', 'order_items.component_id');
}))
->find($id);
return view('orders', compact('order'));
}
我只能用上面的代码生成以下报告
Order No : 1
Order Date : 2015-05-06
Component A 5 USD
Component B 3 USD
但是,我需要以下格式的订单报告,其中包含每个产品组件的产品详细信息。
Order No : 1
Order Date : 2015-05-06
Component A
- Product A 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
我认为我的方向是正确的,但需要指导才能生成所需的报告。
【问题讨论】:
-
Stack Overflow 不是一个让专业开发人员为您编写解决方案的网站。如果您有具体问题,请围绕该问题提出问题,因为此时您的问题过于宽泛。
-
我的具体问题是如何使用嵌套预加载来显示订单报告中显示的产品详细信息。
-
我不会讨论您编写此问题的方式,但请注意:Eloquent 不是适合收集数据的报告的工具。适当使用
Query\Builder和joins。
标签: eloquent laravel-5 eager-loading