Laravel - 如何链接雄辩的关系 - 渴望加载

时间:2017-04-07 17:41:39

标签: php laravel eloquent laravel-5.4

我正在使用来自heremodule.exports = { getAllUsers: getAllUsers, getAllPref: getAllPref, } 关系的Laravel 5.4Laravel Roles

我正在尝试检索公司用户及其角色。

Eloquent为我提供了User::find(1)->roles

的用户角色

id =1获取属于Company::find(1)->users(没有用户角色)的公司的所有用户。

id =1会返回错误Company::find(1)->users->roles

问题

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

    Property [roles] does not exist on this collection instance.

    HasRoleAndPermission.php

    class User extends Authenticatable
    {
        use HasRoleAndPermission;
    
        public function company()
        {
            return $this->belongsTo('App\Company');
        }
    
        public function user()
        {
            return $this->belongsTo(User::class);
        }
    }
    

    Company.php

    trait HasRoleAndPermission
    {
        public function roles()
        {
            return $this->belongsToMany(config('roles.models.role'));
        }
    }
    

2 个答案:

答案 0 :(得分:4)

$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)

1家公司有很多用户。

1个用户有很多角色。

您正在尝试获取用户集合的角色(该属性仅对一个用户存在),因此该集合的属性不存在。

如果您想获得公司所有用户的所有角色,您可以尝试以上代码:

$users = User::with('roles')->where('company_id', $companyId)->get();

---------编辑---------

为了急切加载用户的角色,你必须按照@Ohgodwhy的建议使用$users->roles,但我稍微重构一下:

user

现在您已经有了一系列用户渴望加载他们的角色。您仍然无法直接访问roles,您必须先获得{{1}},然后才能获得{{1}}。