对多行求和,并按组更新或按列更新(拉韦尔埃尔奎恩特)

6ojccjat  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(270)

我想对mysql表中的行求和,然后合并和更新。我想在一天内把所有的重复付款加起来。我将发布我现有的查询,但有一些限制。
例子:

+----+------------+-------------+-------------+---------+
| 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 |
+----+------------+-------------+-------------+---------+

预期结果:

+----+------------+-------------+-------------+---------+
| 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 |
+----+------------+-------------+-------------+---------+

我试过这个循环。

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

问题1。一次只能更新一列。
问题2。我以编程方式遍历行并更新值,因为如果没有重复的值,那么行就不会得到更新。我必须写另一个查询来更新。同时删除现有查询。
问题3。只需付两次钱就行了。
在laravel雄辩地合并(和)多行并更新中有没有可能的解决方案?

zed5wv10

zed5wv101#

试试这个:

$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);

相关问题