在 User.php 模型上我有以下关系:
public function roles()
{
return $this->belongsToMany(Role::class);
}
在数据库中,我有不同的角色,基本上我想返回除“superadmin”角色之外的所有角色,以便它无法显示在 View 中或我选择显示角色的任何位置。
我尝试过类似的方法:
public function roles()
{
return $this->belongsToMany(Role::class)->where('name', '!=', 'superadmin');
}
...但它不起作用。我认为这与数据透视表有关。我也尝试过这个:
public function roles()
{
return $this->belongsToMany(Role::class)->where('role_id, '!=', $id);
}
知道如何做到这一点或者是否可能?
谢谢!
最佳答案
您应该尝试在角色模型上使用范围。
您可以创建一个名为 DisplayRole 的范围,它基本上返回不包括 super 管理员并且可以向用户显示的所有角色。它看起来像这样:
namespace App;
use Illuminate\Database\Eloquent\Model;
class DisplayRole extends Role
{
public function newQuery($excludeDeleted = true)
{
return parent::newQuery($excludeDeleted)->where('name','!=','superadmin');
}
}
然后,您可以像通常使用模型一样使用 DisplayRole(使用 App\DisplayRole),并且在任何需要仅显示用户友好角色的地方,使用该模型而不是基本角色模型。这样,调用 DisplayRole::all() 将返回所有非 super 管理员的角色。
关于php - Laravel Eloquent从belongsToMany()查询中排除特定结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53216270/