TechnicalEloquent performance

Eloquent performanceLesson 15 of 28

Options for Ordering by a HasOne Relationship

hasOne: join first.

1 min readIntermediateLesson

Eloquent performance15

The problem

Sort users by the name of their company, where a user has one company.

The fix

Use a join.

✕ Instead of this

User::orderBy(Company::select('name')
    ->whereColumn('companies.user_id', 'users.id')
    ->take(1)
);   // ~215 ms

✓ Do this

User::join('companies', 'companies.user_id', '=', 'users.id')
    ->select('users.*')
    ->orderBy('companies.name');   // 0.38 ms

The benefit

Hundreds of times faster for a one-to-one sort.

Results

Join

0.38 ms

Subquery

~215 ms

Watch out

  • Add select('users.*'), or Laravel also selects company columns and they can overwrite user columns like id.

Frame from lesson 15

The join approach for hasOne: select users.* from users inner join companies on companies.user_id = users.id order by companies.name runs in 0.38 ms.

Key takeaway

hasOne: join first.

Check yourself

What can go wrong if you leave out select('users.*')?

Reveal answer

✓ Answer

Columns from both tables come back, and same-named columns like id can clash.