【发布时间】:2020-07-03 07:46:51
【问题描述】:
我无法从每个帖子的 role_user 表中获取名称。我有 ACL,所以我有 3 个表 - 用户、角色、角色用户。
我的代码如下所示:
后模型
public function user()
{
return $this->belongsTo(user::class);
}
用户模型。
public function posts()
{
return $this->hasMany(post::class);
}
榜样。
public function users()
{
return $this->hasmany(user::class);
}
后控制器,
return view ('admin.posts',[
'posts' => Post::All()
]);
在刀片中,我通过以下方式回显 fx 用户名:
@foreach ($posts as $post)
<tr>
<th scope="row">{{$post->id}}</th>
<td>{{$post->category->name}}</td>
**<td>{{$post->user->name}}</td>**
</tr>
@endforeach
但问题是我想为写我正在循环的帖子的用户回显角色名称(来自 role_user 表)。
更新
好的,我解决了问题,但可能有更好的 wat。有人吗?
我添加到模型中:
用户模型:
public function roles()
{
return $this->belongsToMany(Role::class);
}
并改变了榜样:
public function users()
{
return $this->belongsToMany(user::class);
}
后控制器:
class PostController extends Controller
{
public function index()
{
return view ('admin.posts',[
'posts' => Post::with('user')->get(),
'roleUsers' => User::with('roles')->get()
]);
}
在刀片中我正在做
@foreach ($posts as $post)
<tr>
<th scope="row">{{$post->id}}</th>
<td>
<p>
@foreach ($roleUsers as $roleUser)
@foreach($roleUser->roles as $role)
<p>
{{ $role->pivot->user_id === $post->user->id ? "Role: $role->name" : "" }}
</p>
@endforeach
@endforeach
我想可能有更好的解决方案。
【问题讨论】: