du7999 2016-07-20 15:36 采纳率: 100%
浏览 97
已采纳

Laravel 5.1 - 通过id和sum值从数据库组中获取数据

Im not sure how to go about this, i need to get data from a table and sum the values of each field together where the ID is the same.

Things I Have Tried

  • Pulled all data and tried to store duplicates in array then sort it like that

$users = User::all();

   $array = [];
    foreach($users as $user)
        {
            array_push($array, [$user->account_id => $user->amount]);
        }
  • Use laravel collections to store the array data and sort it through there

Other than that im not too sure how to go about this! Here is the data that i pull from the database.

0: {1: 100.00}
1: {1: 100.00}
2: {2: 100.00}
3: {2: 100.00}

This is the output i want

0: {1: 200.00}
1: {2: 200.00}

This is all i need nothing else I feel like its really simple but I have no clue, any help and guidance will be appreciated, any further information needed will be provided.

  • 写回答

3条回答 默认 最新

  • douzhang3356 2016-07-20 15:45
    关注

    Try this way:

    <?php
    User::groupBy('account_id')
       ->selectRaw('sum(amount) as sum, account_id')
       ->lists('sum','account_id');
    

    EDIT

    Since ->lists() is now deprecated in laravel 5.2+ it should now be ->pluck(), just for reference

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机