Search code examples
postgresqllaravellaravel-5laravel-5.3postgresql-9.5

How Can I Get SUM Array On Laravel5?


My postgresql database like this.

SELECT * FROM point_records;

 id | user_id | point |     created_at      |     updated_at
----+---------+-------+---------------------+---------------------
  1 |       1 |   100 | 2017-01-27 09:39:47 | 2017-01-27 09:39:47
  3 |       2 |   100 |                     |
  4 |       2 |   100 |                     |
  5 |       3 |   100 |                     |
  6 |       3 |   100 |                     |
  7 |       3 |   100 |                     |

SELECT user_id, SUM(point) AS points FROM point_records GROUP BY(user_id) ORDER BY points desc;

 user_id | points
---------+--------
       3 |    300
       2 |    200
       1 |    100

I wanna get point ranking to array. So now I do this.

$points = \App\PointRecord::selectRaw('member_id, SUM(point) AS points') -> groupBy('member_id') -> orderBy('points', 'desc') -> get() -> toArray();

$your_score = array_search($user -> id, $points) + 1;

this $points array return this.

Array ( [0] => Array ( [user_id] => 3 [points] => 150 ) [1] => Array ( [user_id] => 2 [points] => 100 ) [2] => Array ( [user_id] => 1 [points] => 10 ) )

But I don't wanna use Raw. I'm looking for other ideas.

Anyone knows?


Solution

  • I think your solution is already work why you want to change raw to another. anyway if you really want to change you need to add more code try this

        $outputs = [];
        $query = \App\PointRecord:::groupBy('member_id')->get();
        foreach ($query as $e) {
            $data = $e->toArray();
            $data['point'] = $e->where('member_id', $data["member_id"])->sum('point');
            $outputs[] = $data;
        }
        dd($outputs);