Skip to content
Advertisement

Select DISTINCT returns duplicates data Laravel 8

I’m trying to get groups that belong to a supervisor to be displayed for him. And I’m using join to get each gpid information base on supervisor_id, query its okay but returns duplicate data of the last row. I can’t figure out why it is duplicating the last record. Any help would be much appreciated.

$res = DB::table('tickets')
    ->join('gp_groups', 'tickets.id', '=', 'gp_groups.gpid')
    ->where('gp_groups.supervisor_id', 15)
    ->distinct('gp_groups.gpid')
    ->get();

dd($res);

Result

0 => {#1390 ▼
  +"id": 84
  +"gpname": "G2"
  +"detail": "Mahdi"
  +"gender": "Male"
  +"semester": 432
  +"status": "Not assigned"
  +"Assigned": null
  +"user_id": 19
  +"track_id": 4
  +"created_at": null
  +"updated_at": null
  +"gpid": 71
  +"student_id": 13
  +"supervisor_id": 15
}
1 => {#1396 ▼
  +"id": 83
  +"gpname": "hifjksd"
  +"detail": "hfdjkjs"
  +"gender": "Female"
  +"semester": 431
  +"status": "Not assigned"
  +"Assigned": null
  +"user_id": 1
  +"track_id": 2
  +"created_at": null
  +"updated_at": null
  +"gpid": 73
  +"student_id": 13
  +"supervisor_id": 15
}
2 => {#1353 ▼
  +"id": 109
  +"gpname": "4512"
  +"detail": "8956"
  +"gender": "Male"
  +"semester": 431
  +"status": "Not assigned"
  +"Assigned": null
  +"user_id": 1
  +"track_id": 3
  +"created_at": null
  +"updated_at": null
  +"gpid": 83
  +"student_id": 12
  +"supervisor_id": 15
}
3 => {#1331 ▼
  +"id": 110
  +"gpname": "4512"
  +"detail": "8956"
  +"gender": "Male"
  +"semester": 431
  +"status": "Not assigned"
  +"Assigned": null
  +"user_id": 1
  +"track_id": 3
  +"created_at": null
  +"updated_at": null
  +"gpid": 83
  +"student_id": 13
  +"supervisor_id": 15
}]}

    

Advertisement

Answer

You can try to use groupBy instead of distinct :

$res = DB::table('tickets')
->join('gp_groups', 'tickets.id', '=', 'gp_groups.gpid')
->where('gp_groups.supervisor_id', 15)
->groupBy('gp_groups.gpid')
->get();

dd($res);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement