繁体   English   中英

Laravel-如何建立雄辩的关系-渴望加载

[英]Laravel - How to chain Eloquent relationship - Eager Loading

我正在使用Laravel 5.4Laravel 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.

问题

  1. 有可能做我想做的事吗?
  2. 如果是这样,我该怎么办?

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');
    }
}
$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.

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