-1

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);
x_l_m_25
  • 7
  • 5

2 Answers2

0

You can try with:

Images::max('Version');

You can find more about aggregates here

knubbe
  • 1,132
  • 2
  • 12
  • 21
  • Hi I tried using this way but got an error foreach() argument must be of type array|object, int given. Also wouldn't this way give only one row with the highest version rather than each name's highest version? – x_l_m_25 Apr 14 '22 at 12:56
  • Hm, I don't understand. This one is only related to eloquent aggregates – knubbe Apr 14 '22 at 13:13
0
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.

Huy Phạm
  • 888
  • 9
  • 24
  • These methods are no strange to Laravel so in case you wonder what each method do please consult Laravel Collection documentation – Huy Phạm Apr 15 '22 at 07:11
  • @HuyPham Hi thanks for your reply, if I'm correct, $items=Item::groupBy('model_name')->orderBy("version","DESC")->first() does the same thing as your code? If so this current code shows me all my rows in my table only that they are now in descending order of their versions. Is there any way to change it such that I only want the highest version for each name showing? Something like this question: https://stackoverflow.com/questions/58909566/laravel-group-by-and-order-by-not-working but the answers there aren't working for me. – x_l_m_25 Apr 15 '22 at 10:54
  • No, `$items=Item::groupBy('model_name')->orderBy("version","DESC")->first() ` will only return the first group, only one `name` is shown. – Huy Phạm Apr 15 '22 at 14:49