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);
2
Answers
You can try with:
You can find more about aggregates here
You know what it does.
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).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.