2016-09-30 113 views
0

我创建了一个模块,这些模块包含模块并且每个模块都有价格。多个模块为该服务创建价格。通过父母的Laravel关系

- Service #1 
-- Module 1 ($20) 
-- Module 2 ($40) 

使用belongsToMany

class Services extends Model 
{ 
    public function modules() 
    { 
     return $this->belongsToMany('App\Services\Modules'); 
     ... 

每个模块链接到一个价格

class Modules extends Model 
{ 
    public function price() 
    { 
     return $this->hasOne('App\Services\Pricing', 'product')->where('type', 'module'); 
     ... 

service_module表到模块的链接服务。问题是什么样的关系,我应该创造能够->sum()模块价格为每服务因为我创建了一个难看的补丁与循环和燃烧的每个请求的15多个查询

$prices = []; 
foreach ($services->modules as $modules) 
    $prices[] = $modules ->price['month']; 
$price = number_format(collect($prices)->sum(), 2, '.', ''); 

回答

1

您可以使用Eager Loading加载您的关系以及services查询将这15个额外的查询转换为一个额外的查询。

链接文档中的代码示例应该足以让您开始。