Laravel雄辩的模型 - 按总和过滤

时间:2018-04-06 14:15:30

标签: php laravel laravel-5 eloquent relationship

我有两种模式:

用户:id,姓名,电子邮件

佣金:id,user_id,金额,已付款,退款,created_at

关系:用户有很多佣金

我需要计算每个用户每月的通信总和,并将其下载到CSV文件中以进行批量付款,但这些金额必须大于25且小于25000.

目前我得到了什么,但我如何根据金额范围进行过滤?我需要将那些已经支付的佣金标记为已付款,但只支付那些将超过25且小于25000的佣金

$commissions = Commissions::whereYear('created_at', $date->year)
->whereMonth('created_at', $date->month)
->where('paid', 'no')
->where('refund', 'no')
->get();

我可以通过计算foreach中的数量进行过滤,但我几乎可以肯定Laravel中有一种更优雅的方式可以做到这一点。

2 个答案:

答案 0 :(得分:1)

我认为没有一个简单的解决方案:

$commissions = Commission::whereYear('created_at', $date->year)
    ->whereMonth('created_at', $date->month)
    ->where('paid', 'no')
    ->where('refund', 'no')
    ->where('amount', '<', 25000)
    ->orderByDesc('amount')
    ->get();
$grouped = $commissions->groupBy('user_id');
$grouped = $grouped->filter(function($commissions) {
    return $commissions->sum('amount') > 25;
});
$grouped = $grouped->map(function($commissions) {
    $sum = 0;
    return $commissions->filter(function($commission) use(&$sum) {
        $sum += $commission->amount;
        return $sum < 25000;
    });
});
$commissions = $grouped->collapse();

答案 1 :(得分:0)

使用whereBetween

轻松实现另一种情况
$commissions = $user->commissions()
    ->whereYear('created_at', $date->year)
    ->whereMonth('created_at', $date->month)
    ->where([['paid' , 'no'], ['refund', 'no']])
    ->whereBetween('price', [25, 25000])
    ->sum('price');

或:

$commissions = $user->commissions()
    ->whereYear('created_at', $date->year)
    ->whereMonth('created_at', $date->month)
    ->where([['paid' , 'no'], ['refund', 'no']])
    ->sum('price')->filter(function($value, $key){

        return in_array($value, [25,25000]);

     });