简体   繁体   中英

How should I use Laravel Eloquent queries and use relationships?

I have a User model which belongsTo a Department .

So Department got id and name fields.

At the User model I got:

public function department() {

      return $this->belongsTo('Department');
}

That way I can do something like: Auth::user()->department->name getting the actual name of the department user belongs to.

However, when I'm calling some users, I can't figure out best way to get multiple rows containing its department attribute with a name.

I wrote:

$users = User::all();
foreach ($users as $user) {
    $user -> department = Department::find($user->department_id)->name;
}

Is there a better way to do this?

You can eager load related models so they are loaded for all users with only one database query and will be included in JSON output:

$users = User::with('department')->get();

More about eager loading in the Laravel Docs

It seems that you got the relationship between User Model and Department Model already. So you can call it like you did with Auth().

$users = User::all();
foreach ($users as $user) {
    echo $user->department->name ;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM