我在从role_user表中获取每个帖子的名称时遇到问题。我有ACL,所以我有3个表-用户,角色,role_user。
我的代码如下所示:
发布模型
public function user()
{
return $this->belongsTo(user::class);
}
用户模型。
public function posts()
{
return $this->hasMany(post::class);
}
好榜样。
public function users()
{
return $this->hasmany(user::class);
}
PostController,
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表)。
更新
好的,我解决了问题,但是可能有更好的方法。任何人?
我添加了模型:
用户模型:
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
我想可能会有更好的解决方案。
withPivot()
在关系上使用方法。如果通过多对多关系来获取数据,它将在模型上,而不是从数据透视表属性中获取。
public function users()
{
return $this->belongsToMany(user::class)->withPivot();
}
然后,我将把前端逻辑更改为样式的东西,假设所有帖子都将有一个具有给定角色的用户,否则您将需要进行if检查。
@foreach ($roleUsers as $roleUser)
{{ $roleUser->roles->where('id', $post->user->id)->first()->name }}
@endforeach
您的问题有很多代码,但这是我的理解方式,希望它可以使您更深入地了解它。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句