douzhang1955 2015-07-19 12:38
浏览 72
已采纳

通过在Table1.id上应用groupBy但在Table2上没有软删除行,使用Laravel Query Builder计算总和?

I want to get all the purchases and their sums and also I don't want to add the amount if payments.deleted_at is not null.

Here are the tables

purchases

id | name
1  | Gamerzone Book
2  | Recipe Book
3  | EngineX Book

payments

id  | purchase_id  | amount  | deleted_at
1     1              100       2015-06-12 11:00:00
2     2              50        NULL
2     2              10        NULL

Code

$query = DB::table('purchases')
        ->select(['purchases.*',
                   DB::raw("IFNULL(sum(payments.amount),0) as total")
            ])
         ->leftJoin('payments','payments.purchase_id','=','purchases.id')
         ->whereNull('payments.deleted_at')
         ->groupBy('purchases.id')->get();

When I run the code below the 1st result is not included. Result

id | name               | total
2  | Recipe Book          60 
3  | EngineX Book         0

I know why It is not included but the problem is if I remove whereNull('payments.deleted_at') that particular row in payments will also add to the sum.How should I solve this ??

Expected Result

id | name               | total
1  | Gamerzone Book       0
2  | Recipe Book          60 
3  | EngineX Book         0
  • 写回答

1条回答 默认 最新

  • douji8017 2015-07-19 13:53
    关注

    In this case your join condition should looks like this:

    ON (payments.booking_id = purchases.id AND payments.deleted_at IS NOT NULL)

    And it is not about WHERE (according to your SELECT). You should use join-closure like this:

    $query = DB::table('purchases')
    ->select(['purchases.*', DB::raw("IFNULL(sum(payments.amount),0) as total")])
    ->leftJoin('payments', function($join) {
        $join->on('payments.booking_id', '=', 'purchases.id');
        $join->on('payments.deleted_at', 'IS', DB::raw('NOT NULL')); 
    })
    ->groupBy('purchases.id')->get();
    

    Just replace

    ->leftJoin('payments','payments.booking_id','=','purchases.id')
    

    with

    ->leftJoin('payments', function($join) {
        $join->on('payments.booking_id', '=', 'purchases.id');
        $join->on('payments.deleted_at', 'IS', DB::raw('NOT NULL')); 
    })
    

    and remove this:

    ->whereNull('payments.deleted_at')
    

    it should help.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集