muflih karim
muflih karim

Reputation: 43

Laravel Group By and Order By not working

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

Upvotes: 0

Views: 5224

Answers (2)

Mdr Kuchhadiya
Mdr Kuchhadiya

Reputation: 461

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');

Upvotes: 3

Zar Ni Ko Ko
Zar Ni Ko Ko

Reputation: 352

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

Upvotes: 2

Related Questions