Home > other >  How do I display the highest value of the column in Laravel using Eloquent?
How do I display the highest value of the column in Laravel using Eloquent?

Time:04-15

I am trying to display rows that show the highest Version of each Name. However, I'm having problems on how to convert my raw php code to Eloquent ORM. Any help will be appreciated.

$sql="SELECT * FROM images WHERE (Name,Version) IN (SELECT Name, MAX(Version) FROM images GROUP by Name)";

Edit:

This is my code that I tried so far, it shows unique names but it doesn't show the name's highest version.

$items=Item::orderBy("version","DESC")->groupBy('model_name')->latest()->paginate(5);

CodePudding user response:

You can try with:

Images::max('Version');

You can find more about aggregates here

CodePudding user response:

Image::all()
->groupBy('model_name')
->map(function($group) { return $group->sortByDesc('version')->first(); });

Image::all()

You know what it does.

->groupBy('model_name')

Group by model_name. Replace the field name with by which field you want to group them. So there are how many models, there are that many group(s).

->map(function($group) { return $group->sortByDesc('version')->first(); });

In each group, to get the item (not items) latest version, I'm sorting them descending by version. This way item with the latest version will be at the top. Then take it.


If you want multiple items with the latest version, adapt.

  • Related