2016-09-30 6 views
0

모듈로 포장 된 서비스에 대한 모델을 만들었으며 각 모듈에는 가격이 있습니다. 여러 모듈이 해당 서비스의 가격을 만듭니다. 가격부모를 통한 Laravel 관계

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

belongsToMany

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

각 모듈과 연결 모듈을 연결하는 서비스 service_module 표를 사용

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

. 문제는 내가 못생긴 루프와 패치 요청에 따라 15 개 쿼리를 굽기를 생성하기 때문에 각 서비스모듈 가격을 ->sum() 할 수 있도록 만들어야합니다 관계의 어떤 종류의

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

답변

1
사용할 수

Eager Loading을 사용하여 services 쿼리와 함께 관계를로드하면 15 개의 추가 쿼리가 하나의 추가 쿼리로 바뀝니다.

링크 된 문서의 코드 예제로 시작하는 데 충분해야합니다.