0

I tried to make a Laravel 5.8 project, and the data in the project is like this :

id  |purch| name         |  prcvalue
------------------------------------
1   |10234| Nabila       | 100
2   |10234| Nadeera      | 450
3   |10234| Nabila       | 540
4   |10234| Nadeera      | 480

then i need to show that data like this :

id  |purch| name         |  prcvalue
------------------------------------
3   |10234| Nabila       | 540
4   |10234| Nadeera      | 480

I have tried using GroupBy = name and OrderBy prcvalue DESC but it just return :

id  |purch| name         |  prcvalue
------------------------------------
1   |10234| Nabila       | 100
2   |10234| Nadeera      | 450

does anyone know how i can get the results that i need? here my code :

myModel::where('purch','=','10234')
      ->orderBy('prcvalue','DESC')
      ->groupBy('name')
      ->get();

many thanks

muflih karim
  • 33
  • 1
  • 3

2 Answers2

3

If You want the latest id of records then you can use unique() after get(), don't use group by if you use groupBy then you lose your control from id. I hope this is useful for you

myModel::select('id','purch','name','prcvalue')
  ->where('purch','=','10234')
  ->orderBy('prcvalue','DESC')
  ->get()
  ->unique('name');

Mdr Kuchhadiya
  • 431
  • 4
  • 12
2

I think you need max value ,

  myModel::select('id','purch','name',DB::raw("MAX(prcvalue) as prcvalue"))
  ->where('purch','=','10234')
  ->orderBy('prcvalue','DESC')
  ->groupBy('name')
  ->get();

And if it still not working , edit in config/database.php. In mysql array , set to strict => false

Zar Ni Ko Ko
  • 352
  • 2
  • 7