对于Eloquent,我有一个潜在的基本问题。我只想显示与该用户的角色相对应的名称。我使用了雄辩的关系ManytoMany。但我不能让它起作用。
我尝试使用$users
参数指向该名称,但这不起作用。
我的项目有三个文件,例如视图角色模型,StudentController,。
谢谢。
角色模型
class Role extends Model
{
protected $fillable = ['id','role_name','role_level','role_note'];
public function users()
{
return $this->belongsToMany('App\User', 'role_users', 'user_id', 'role_id');
}
}
我的StudentController
class StudentController extends Controller
{
public function find_username()
{
$roles = Role::all();
foreach($roles as $role)
{
echo $role->users . '<br>';
}
return view('find_username',['roles'=> $roles]);
}
}
My find_username视图
@extends('master')
@section('content')
<div class="row">
<table class="table">
<thead>
<tr>
<th>ID Role</th>
<th>Role name</th>
<th>Role level</th>
<th>Role note</th>
<th>User name</th>
</tr>
</thead>
<tbody>
@foreach ($roles as $item)
<tr>
<td>{{$item['id']}}</td>
<td>{{$item['role_name']}}</td>
<td>{{$item['role_level']}}</td>
<td>{{$item['role_note']}}</td>
<td>{{$item->users}}</td>
</tr>
@endforeach
</tbody>
</table>
</div>
@endsection
https://stackoverflow.com/questions/57036543
复制相似问题