laravel get one of each duplicate column

564 Views Asked by At

The structure of the table in the database is as follows:

id body user_id group_id
1 test1 1 1
2 test1 2 1
3 test1 3 1
3 test2 4 2
4 test3 5 3

I want to get the first row from each group_id with Eloquent/DB Facade or MongoDB Query in Laravel with paginate:

For Example:

id body user_id group_id
1 test1 1 1
3 test2 4 2
4 test3 5 3

How is this achievable?

2

There are 2 best solutions below

0
On

for Mongodb use this aggregation

[
  {
    $sort:{
       group_id: 1,
       user_id:1
    }
  },
  {
    '$group': {
      '_id': {
        'group_id': '$group_id'
      }, 
      'a': {
        '$first': '$$ROOT'
      }
    }
  }
]
0
On

Use Eloquent's GroupBy as below, it will fetch the first record from the same group:

DB::table('tablename')
    ->groupBy('group_id')
    ->get();