Sort users by the name of their company, where a user has one company.
Join
0.38 ms
Eloquent performanceLesson 15 of 28
hasOne: join first.
1 min readIntermediateLesson
Sort users by the name of their company, where a user has one company.
Use a join.
User::orderBy(Company::select('name')
->whereColumn('companies.user_id', 'users.id')
->take(1)
); // ~215 ms
User::join('companies', 'companies.user_id', '=', 'users.id')
->select('users.*')
->orderBy('companies.name'); // 0.38 ms
Hundreds of times faster for a one-to-one sort.
Join
0.38 ms
Subquery
~215 ms
select('users.*'), or Laravel also selects company columns and they can overwrite user columns like id.
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.
hasOne: join first.
What can go wrong if you leave out select('users.*')?
✓ Answer
Columns from both tables come back, and same-named columns like id can clash.