【问题标题】:LARAVEL 5.3, Get User Name and Role Name (Using Laravel Model Relationships)LARAVEL 5.3,获取用户名和角色名(使用 Laravel 模型关系)
【发布时间】:2017-04-03 22:41:00
【问题描述】:

测试语法或拼写错误 ► 澄清含义而不改变它 ► 纠正小错误 ► 添加相关资源或链接 ► 永远尊重原作者

【问题讨论】:

  • 看起来你需要定义一个多对多的关系。 function roles(){return $this->belongsToMany(Role::class, 'user_role');}
  • @PaulSpiegel 在用户模型public function roles() { return $this->hasMany(UserRole::class); } 上还不够@

标签: php laravel model relationship


【解决方案1】:

使用eager loading获取数据:

$user = User::where('id', $userId)->with('roles')->first();

然后显示数据:

{{-- Display full name --}}
{{ $user->first_name.' '.$user->last_name }}

{{-- Display all role names of the user --}}
@foreach ($user->roles as $role)
    {{ $role->name }}
@endforeach

我猜这里的关系是多对多的,所以你需要将roles()关系更改为belongsToMany()

如果您正在使用一些具有多对多关系的包,但您只为用户附加了一个角色,您可以使用以下内容显示角色名称:

{{ $user->roles->first()->name }}

另外,您可以使用accessor 获取全名:

public function getFullNameAttribute($value)
{
    return $this->first_name.' '.$this->last_name;
}

使用访问器显示全名:

{{ $user->full_name }}

【讨论】:

  • 嘿,谢谢伙计!我需要所有用户(所以没有用户 ID),但我想得到它。但是,` {{$userrole->role->name}} //--工作正常 @foreach ($userrole->role as $role) {{ $role->name }} // 抛出错误 @endforeach ` ANY想法??
  • @Vinuvasudev 为什么你使用$userrole 而不是$user
  • 实际上是在用户角色链接(所以 userrole).. 列出所有用户及其角色的单个页面!并且角色可以是多个(一对多)
  • @Vinuvasudev 您需要获取所有用户及其角色,因此您需要在此处使用User 模型。 User::with('roles')->get(); 然后迭代 $users。另外,由于您有带有user_idrole_id 的数据透视表,它是many to many relationship,您应该使用belongsToMany()
  • 我有一个用户角色表(你可以在那里看到我的 UserRole 模型)所以需要列出所有用户、角色!目前一切正常,除了很多!但是当我输入belongToMany 时,出现一个显示不存在表名和所有表名的sql 查询错误
【解决方案2】:
@foreach($users as $user)
{{$user->name}}  {{$user->roles->first()->name}}

@endforeach

【讨论】:

    猜你喜欢
    • 2017-03-17
    • 2020-07-03
    • 2017-09-16
    • 2016-12-26
    • 1970-01-01
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2021-01-05
    相关资源
    最近更新 更多