تماشای این درس نیاز به اشتراک حرفه‌ای دارد.

Ordering by Related Column0:00

In this lesson, we're going to look at how we can order records by the value of a belongsTo relationship column. Consider this page which lists all the Users in this app with their name, email address, and company name. Currently, our 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 remove the existing name orderBy. Now, let's add a join for the companies table where the company_id is equal to the users.company_id.

Join-Based Ordering0:25

Let's go to our UsersController and remove the existing orderBy. Now, let's add a join for the companies table where the company_id is equal to the users.company_id. However, we'll need to add a select statement now since by default, Laravel will automatically select all the columns from both the users and companies tables. And finally, we'll orderBy 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, let's now 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.

Subquery-Based Ordering0:59

This time, instead of using a join to pull in the company's table data, we're going to use a subquery to get this information instead. We'll order by from the company table. Now, just remember to import that. We'll select the name where the company_id is equal to the users company_id. Then, we'll order by the company name and take the first record. And now, if we hit refresh in the browser, 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 as fast as the join approach, running at about 77 milliseconds. So, when ordering a belongsTo relationship, definitely reach for the join approach first.

Performance Comparison Summary1:31

running at about 77 milliseconds. So, when ordering a belongsTo relationship, definitely reach for the join approach first.

JoinsSubqueries

دوست دارید گاهی خبرهای Laracasts را ایمیل کنیم؟