Sort users by their company name, where a user belongs to a company.
Join
<1 ms
Eloquent performanceLesson 16 of 28
belongsTo: join first.
1 min readIntermediateLesson
Sort users by their company name, where a user belongs to a company.
Use a join, same as hasOne but with the keys the other way round.
User::orderBy(Company::select('name')
->whereColumn('companies.id', 'users.company_id')
); // ~77 ms
User::join('companies', 'companies.id', '=', 'users.company_id')
->select('users.*')
->orderBy('companies.name'); // under 1 ms
Under 1 ms instead of ~77 ms.
Join
<1 ms
Subquery
~77 ms
belongsTo: join first.
What's the only difference from the hasOne join?
✓ Answer
Which side holds the foreign key: users.company_id instead of companies.user_id.