douchuilai2355 2018-04-28 03:22
浏览 106

对多行求和并按列按列进行更新。 (Laravel雄辩)

I want to SUM rows in MySQL table then merge and update. I'm trying to sum all the duplicate payments in a day. I will post my existing query but there are some limitations.

Example:

+----+------------+-------------+-------------+---------+
| id |    date    | merchant_id | investor_id | payment |
+----+------------+-------------+-------------+---------+
|  1 | 27/05/1989 |           4 |           7 |    1000 |
|  2 | 27/05/1989 |           4 |           7 |    1200 |
|  3 | 28/05/1989 |           4 |           7 |    1500 |
|  4 | 28/05/1989 |           4 |           7 |    1000 |
|  5 | 28/05/1989 |           5 |           8 |    1000 |
+----+------------+-------------+-------------+---------+

Expected result:

+----+------------+-------------+-------------+---------+
| id |    date    | merchant_id | investor_id | payment |
+----+------------+-------------+-------------+---------+
|  1 | 27/05/1989 |           4 |           7 |    2200 |
|  3 | 28/05/1989 |           4 |           7 |    2500 |
|  5 | 28/05/1989 |           5 |           8 |    1000 |
+----+------------+-------------+-------------+---------+

I tried this loop.

foreach ($existing_payments as $key => $payment) 
{
    ParticipentPayment::where('payment_date',$payment->payment_date) ->update(['payment' => \DB::raw("payment+$payment->payment"]);
}      

Problem 1. I can only update one column at a time.

Problem 2. I'm programmatically looping through the rows and updating value, because of that if there is no duplicate value then the row not getting updated. I have to write another query to update. To delete existing query also.

Problem 3. It works well only for two payments.

Is there any possible solution in laravel eloquent merge(with sum) multiple rows and update?

  • 写回答

1条回答 默认 最新

  • douqipi9704 2018-04-28 22:18
    关注

    Try this:

    $delete = [];
    $payments = ParticipentPayment::selectRaw("GROUP_CONCAT(`id` SEPARATOR ',') `ids`")
        ->selectRaw('SUM(`payment`) `sum`')
        ->groupBy('date', 'merchant_id', 'investor_id')
        ->get();
    foreach($payments as $payment)
    {
        $ids = explode(',', $payment->ids);
        if(count($ids) == 1) continue;
        ParticipentPayment::whereKey($ids[0])->update(['payment' => $payment->sum]);
        $delete = array_merge($delete, array_slice($ids, 1));
    }
    ParticipentPayment::destroy($delete);
    
    评论

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧
  • ¥15 #MATLAB仿真#车辆换道路径规划