如何在雄辩的Laravel关系中获得另一个总和

时间:2019-05-01 01:52:28

标签: laravel eloquent laravel-5.5

我有一个关系user->sales->detail_sales,一个用户有一个或多个销售,一个销售有一个或多个详细信息。我想做的是从 ELOQUENT 获得,每个用户的所有销售额的总和,即用withCount使计算出的总收入达到sum(totaldetails)

Sale.php

public function detail()
{
    return $this->hasMany(Detail:class);
}


public function user()
{
    return $this->belongsTo('App\User');
}

DetailSale

public function sale()
{
    return $this->belongsTo(Sale::class);
}

用户

public function sales()
{
    return $this->hasMany(Sale::class );
}

我目前有这个查询

return App\User::with(['sales' => function($query){
    // get total for detail_sales for sale
    $query->withCount(['detail as totaldetails' => function($que){
        $que->select(DB::raw('sum(subtotal)'));
    }]);
}])->get();

但是我希望在用户模型中拥有例如 salestotal 之类的属性,

@foreach($users as $user)
  {{ $user->salestotal}}
@endforeach

3 个答案:

答案 0 :(得分:1)

您可以将withCount()HasManyThrough关系一起使用:

class User extends Model
{
    public function details()
    {
        return $this->hasManyThrough(Detail:class, Sale::class);
    }
}

return App\User::withCount(['details as salestotal' => function($query) {
    $query->select(DB::raw('sum(subtotal)'));
}])->get();

@foreach($users as $user)
    {{ $user->salestotal }}
@endforeach

答案 1 :(得分:0)

为什么不只使用sum()函数,因为它都在集合中?

@foreach($users as $user)
    {{ $user->sales->sum('totaldetails') }}
@endforeach

答案 2 :(得分:0)

我希望这会有所帮助:

    return App\User::with(['sales' => function($query){
     // get total for detail_sales for sale
        $query->withCount(['detail as totaldetails' => function($que){
       $que->select(DB::raw("SUM(subtotal) as salestotal"));
       }]);
    }])->get();