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 2024-五一综合模拟赛
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测
  • ¥15 ETLCloud 处理json多层级问题
  • ¥15 matlab中使用gurobi时报错
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭