For a project I’m working on, I really needed to do a groupwise max in Laravel. If you’re here, you likely don’t need an explanation of what that is, so much as how to actually bloody do it, so without further delay;
Let’s say that we have Actions, and we have an ActionLog, and you want to get the latest ActionLog entry for a series of Actions – determined by their “timestamp” field. You would write this:
1 2 3 |
$query = DB::raw('select * from (' . ActionLog::whereIn('action_id', [1, 2, 3])->orderBy('timestamp', 'desc')->toSql() . ') group by `action_id`'); |
Unfortunately there’s no way to do it without the dreaded DB::raw, but otherwise it turns out to be pretty simple.