-1

I am working on a leaderboard and each user has many records on the leaderboards table. Here's the object it returns

[
  {
    "user_id": 3,
    "user_name": "Langosh Troy",
    "points": 78
  },
  {
    "user_id": 3,
    "user_name": "Langosh Troy",
    "points": 76
  },
  {
    "user_id": 1,
    "user_name": "Crooks Elsa",
    "points": 12
  }
]

But I want it to appear such that the object with user_id = 3 would become one object so my final return value should look this way

[
  {
    "user_id": 3,
    "user_name": "Langosh Troy",
    "points": 154
  },
  {
    "user_id": 1,
    "user_name": "Crooks Elsa",
    "points": 12
  }
]
chinedu
  • 17
  • 4
  • What have you tried and what error are you facing ? – Sehdev Feb 25 '20 at 15:55
  • I have thought of ways to merge is and i don't know if there's a laravel helper that can do it. Went through the documentation and couldn't find – chinedu Feb 25 '20 at 16:00

2 Answers2

0

use something similar to this:

UserPoints::groupBy(['user_id','user_name'])
   ->selectRaw('sum(points) as sum, user_id, user_name')
   ->get();

What we are doing here is using database group functions that allow us to group certain database rows into a single row and use some of group functions. (sum is adding all values of points field, count would count number of rows for each user, max would give the row with max number of points per user)

Have a look at all the group functions mysql offers:

https://dev.mysql.com/doc/refman/8.0/en/group-by-functions.html

MaxT
  • 211
  • 1
  • 4
0

If you want use a Eloquent Query then try this:

$records = User::query()->select(['sum(points) as points','user_id','user_name'])
 ->letfJoin('leaderboard','user_id','=','user.id')->groupBy(['user_id','user_name'])->get();

Also if you want handled it as array should by like this

$users = User::all();
$result=[];
foreach($users as $user){
   $result[]=['user_id'=$user->id,'user_name'=>$user->name, 'points'=>$user->leaderboards()->sum('points')];
}

Very important the best way is by Eloquent query