Ordering by Related Column0:00
In this lesson, we're going to look at how we can order records by the value of a hasOne relationship column. Consider this page which lists all the Users in this app with their name, email address, and their company name. Currently, this page is ordering the Users by their name. However, what if we wanted to order them by their company name instead? How would we do this? There's actually two approaches we can use. The first is using a join and the second is using a subquery. Let's try the join approach first. Let's go to our UsersController and let's remove the existing name orderBy. Now, let's add a join for the companies table where the company_id equals the user_id.
Subquery Ordering Approach0:25
Let's go to our UsersController and let's remove the existing name orderBy. Now, let's add a join for the companies table where the company_user_id equals the users.id. However, we need to add a select statement now since by default Laravel will select all the columns from both the users and companies tables. And finally, we'll order these records by the company.name. And now if we hit refresh in the browser, we can see that it's working. And if we look at the Laravel debug bar, we can see that this query is running in less than one millisecond. Okay, now let's take a look at the subquery approach. This time, instead of using a join to pull in the companies table data, we're going to use a subquery to get this information instead. orderBy from the companies table and we'll make sure we import that right away. And we'll select the name where the companies.user_id column equals our users.id.
Performance Comparison Conclusion1:04
Order by from the company's table and we'll make sure we import that right away. And we'll select the name where the company's user_id column equals our users id. Then we'll order that by the company name and then we'll get the first record. And now if we hit refresh in the browser again, we can see that it's still working. However, if we look at the Laravel debug bar, we can see that this approach isn't nearly as fast as a join approach running at about 215 milliseconds. So when ordering a hasOne relationship, definitely reach for the join approach first.
