[英]Laravel - eager loading a method (not a relationship) of an Eloquent model
[英]Laravel - How to chain Eloquent relationship - Eager Loading
我正在使用Laravel 5.4
, Laravel Roles
和此处的 Eloquent
关系。
我正在尝试检索公司的用户及其角色。
User::find(1)->roles
我获取id =1
的用户角色
Company::find(1)->users
我提供了id =1
的公司的所有用户(无用户角色)。
Company::find(1)->users->roles
返回错误Property [roles] does not exist on this collection instance.
class User extends Authenticatable
{
use HasRoleAndPermission;
public function company()
{
return $this->belongsTo('App\Company');
}
public function user()
{
return $this->belongsTo(User::class);
}
}
trait HasRoleAndPermission
{
public function roles()
{
return $this->belongsToMany(config('roles.models.role'));
}
}
class Company extends Model
{
public function users() {
return $this->hasMany('App\User');
}
}
$company = Company::with('users.roles')->find(1);
将加载所有用户,以及每个用户的所有角色。
更新资料
根据您的评论,您不需要公司数据。 只是用户和角色使用渴望的加载和关系存在。
$users = User::with('roles')
->whereHas('company' => function($query){
$query->where('name', '=', 'company'); //If you don't have the company ID
})->get();
没有关系存在
$users = User::where('company_id', 1)->with('roles')->get();
1家公司有许多用户。
1位用户具有多个角色。
您正在尝试获取用户集合的角色(该属性仅对一个用户存在),因此该集合不存在该属性。
如果要获得公司中所有用户的所有角色,则可以尝试上面的代码:
$roles = [];
Company::find(1)->users->foreach(function($user) {
$roles = array_merge($roles, $user->roles);
});
---------编辑---------
对于预先加载用户的角色,必须使用with
由@Ohgodwhy的建议,但我重构了一点:
$users = User::with('roles')->where('company_id', $companyId)->get();
现在,您拥有一系列渴望加载其角色的用户。 您仍然不能直接访问$users->roles
,您必须首先获得一个user
,然后才能获得其roles
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.