dongsheng8664 2017-04-07 17:41
浏览 27
已采纳

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

I'm using Laravel 5.4, Laravel Roles from here and Eloquent relationships.

I'm trying to retrieve the users of a company along with their roles.

User::find(1)->roles gets me the user's roles whose id =1

Company::find(1)->users gets me all the users that belongs to the company whose id =1 (without the roles of users).

Company::find(1)->users->roles returns an error Property [roles] does not exist on this collection instance.

Questions

  1. Is it possible to do what I want to do ?
  2. If so, how should I do it ?

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');
    }
}
  • 写回答

2条回答 默认 最新

  • dongwei5740 2017-04-07 17:45
    关注

    1 company has many users.

    1 users has many roles.

    You are trying to get the roles of a collection of users (the property only exists for one user) thus, the property doesn't exists for the collection.

    If you want to get all the roles of all users in the company, you might try the above code:

    $roles = [];
    Company::find(1)->users->foreach(function($user) {
        $roles = array_merge($roles, $user->roles);
    });
    

    --------- edit ---------

    For eager loading the roles of users, you must use with, as suggested by @Ohgodwhy, but I'd refactor a little:

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

    Now you have the array of users eager loading their roles. You still can't access directly $users->roles, you must first get a user, only then get its roles.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动