php - Laravel - How to chain Eloquent relationship - Eager Loading -
i'm using laravel 5.4
, laravel roles
here , eloquent
relationships.
i'm trying retrieve users of company along roles.
user::find(1)->roles
gets me user's roles id =1
company::find(1)->users
gets me users belongs company id =1
(without roles of users).
company::find(1)->users->roles
returns error property [roles] not exist on collection instance.
questions
- is possible want ?
- if so, how should ?
user.php
class user extends authenticatable { use hasroleandpermission; public function company() { return $this->belongsto('app\company'); } public function user() { return $this->belongsto(user::class); } }
hasroleandpermission.php
trait hasroleandpermission { public function roles() { return $this->belongstomany(config('roles.models.role')); } }
company.php
class company extends model { public function users() { return $this->hasmany('app\user'); } }
1 company has many users.
1 users has many roles.
you trying roles of collection of users (the property exists 1 user) thus, property doesn't exists collection.
if want roles of users in company, might try above code:
$roles = []; company::find(1)->users->foreach(function($user) { $roles = array_merge($roles, $user->roles); });
--------- edit ---------
for eager loading roles of users, must use with
, suggested @ohgodwhy, i'd refactor little:
$users = user::with('roles')->where('company_id', $companyid)->get();
now have array of users eager loading roles. still can't access directly $users->roles
, must first user
, roles
.
Comments
Post a Comment