Support the ongoing development of Laravel.io →
Database Eloquent Forms
Last updated 1 year ago.
0
Solution

i'm still new and can't get a good hold of the relationships and eager loading. but you can use join to do the same thing

$manager = User::join('teams', 'teams.manager_id', '=', 'users.id')->orderBy('teams.manager_id')->lists('users.username', 'teams.manager_id');

assuming i read your relationship right. i don't know why i can't seem to understand relationships and eager loading in laravel, but i hope this works for you.

Last updated 1 year ago.
0

Eager loading isn't too hard to understand. Suppose you have an eloquent collection you are looping over, it has 20 users. One of the fields on the user table is country_id. You define a relationship on the users model, each user has one country. So without eager loading, each time you loop over the users in the view and display their country, it needs to join the country table. This is the n+1 problem. Instead, you can eager load the countries ahead of time.

User::with('country')->take(20)->get();

You can dump your queries and you'll see the difference when you use eager loading.

foreach (DB::getQueryLog() as $query) {
    var_dump($query);
}
Last updated 1 year ago.
0

Just a quick note to thank you both, both answers have proved useful :)

Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

matbow matbow Joined 19 May 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.