TechnicalEloquent performance

Eloquent performanceLesson 17 of 28

Options for Ordering by a HasMany Relationship

hasMany: subquery first. It's cleaner and here faster.

1 min readIntermediateLesson

Eloquent performance17

The problem

Sort users by their most recent login. A join returns a row per login: 30,000 rows instead of 60.

The fix

Use a subquery that gets each user's latest login date.

✕ Instead of this

User::join('logins', 'logins.user_id', '=', 'users.id')
    ->select('users.*')
    ->orderByDesc('logins.created_at');
// one row per login: 30,000 rows for 60 users

✓ Do this

User::orderByDesc(Login::select('created_at')
    ->whereColumn('logins.user_id', 'users.id')
    ->latest()
    ->take(1)
);

The benefit

One row per user, no grouping, and the fastest option here (~25 ms).

Results

Join + group by

~42 ms

Subquery

~25 ms

More detail

The join version also works, but needs grouping and an aggregate so MySQL knows which of the 500 dates to use:

User::join('logins', 'logins.user_id', '=', 'users.id')
    ->groupBy('users.id')
    ->orderByRaw('max(logins.created_at) desc');

Frame from lesson 17

The subquery approach for hasMany: order by (select created_at from logins where user_id = users.id order by created_at desc limit 1) desc. Users are ordered by most recent login, with no GROUP BY or duplicate rows to deal with.

Key takeaway

hasMany: subquery first. It's cleaner and here faster.

Check yourself

Why does MySQL error when you add groupBy('users.id') but order by logins.created_at?

Reveal answer

✓ Answer

Each user now has many dates in one group, and MySQL doesn't know which one to sort by. Use max().