编辑:
我已经测试了第二种解决方案,它似乎工作得很好。我确实带来了一个小变化;这就是改变
categories
到
category
。以下是更新后的代码:
$posts = Post::whereHas('user.roles', function($q){
return $q->whereLabel('is-admin');
})->with('category')->get();
我假设你的关系定义类似于以下内容(仅显示必要的关系):
之前注意:角色和用户具有多对多关系,因为一个用户可以有多个角色,一个角色可以属于多个用户。因此,数据透视表role_user位于角色和用户表之间,用于管理用户角色。
在用户模型中:
public function roles()
{
return $this->belongsToMany(Role::class);
}
榜样:
public function users()
{
return $this->belongsToMany(User::class);
}
岗位模型:
public function user()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->belongsTo(Category::class);
}
基本上,用户有许多角色,类别与角色无关,在这种情况下,也与用户无关。那么,为什么不尝试根据用户角色选择帖子,然后快速加载类别呢。试试看:
Post::with(['user.roles' => function ($query) {
$query->whereLabel('is-admin');
}])->with('categories')->get();
//OR
Post::whereHas('user.roles', function ($query) {
$query->whereLabel('is-admin');
})->with('categories')->get();