TechnicalEloquent performance

Eloquent performanceLesson 16 of 28

Options for Ordering by a BelongsTo Relationship

belongsTo: join first.

1 min readIntermediateLesson

Eloquent performance16

The problem

Sort users by their company name, where a user belongs to a company.

The fix

Use a join, same as hasOne but with the keys the other way round.

✕ Instead of this

User::orderBy(Company::select('name')
    ->whereColumn('companies.id', 'users.company_id')
);   // ~77 ms

✓ Do this

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

The benefit

Under 1 ms instead of ~77 ms.

Results

Join

<1 ms

Subquery

~77 ms

Key takeaway

belongsTo: join first.

Check yourself

What's the only difference from the hasOne join?

Reveal answer

✓ Answer

Which side holds the foreign key: users.company_id instead of companies.user_id.