>我有 4 张桌子,配件连接在套件中:
Accessories
id name price
1 accessory1 43
2 accessory2 31
3 accessory3 13
4 accessory4 9
AccessoriesKit (table store relation between Accessories and KitMain)
id id_accessories id_accessories_kit_main
1 1 1
2 2 1
3 3 2
4 4 2
AccessoriesKitMain
id name
1 kit1
2 kit2
AccessoriesKitMainRelatedToProduct (table store relation between Product with their all accessories kits)
id id_accessories_kit_main id_product
1 1 2
2 2 1
我的问题是什么 - 我按产品ID获得与产品相关的配件套件,我需要将主套件中包含的每个配件的价格相加并显示在视图中。
这就是我获取配件的方式——
$accessories = AccessoriesKitMainRelatedToProduct ::where('id_product', '=', $products[0]['id'])
->with('accessorieskitmain', 'accessorieskitmain.accessorieskit', 'accessorieskitmain.accessorieskit.accessories')->get()->toArray();
如何对价格求和并将其分组到相关套件中?
编辑
我在控制器中获取数组 - $accessories 个附件并将其传递给我的模板,在那里我循环使用它:
@foreach($accessories as $accessory)
@foreach($accessory['accessories_kit_main'] as $kitMain)
<div class="accessory-title">
<h2>{{$kitMain['name']}}</h2>
</div>
@foreach($kitMain['accessories_kit'] as $kit)
@foreach($kit['accessories'] as $singleAccessories)
<div>
<h2> {{$singleAccessories['name']}}</h2>
<h2> {{$singleAccessories['price']}}</h2>
</div>
@endforeach
@endforeach
!! AND HERE I NEED TO PUT SUMMED UP PRICES !!
@endforeach
@endforeach
$accessories = AccessoriesKitMainRelatedToProduct::where('id_product', '=', $products[0]['id'])
->with(['accessorieskitmain',
'accessorieskitmain.accessorieskit',
'accessorieskitmain.accessorieskit.accessories' => function($query){
$query->sum('price');
}])
->get()->toArray();
希望它对你有用!!