php - Laravel Eloquent从belongsToMany()查询中排除特定结果

标签 php mysql laravel eloquent has-and-belongs-to-many

在 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/

相关文章:

mysql - 如何连接在独立容器上运行的Wordpress和MySql

PHP session 超时为 0,但 session 仍将过期

php - 从 Mysql 数据库中插入和检索图像

php - 如何在 PHP 中以特定用户身份运行外部命令

MySQL - 搜索特定值的多个模式

mysql - 将父查询列值传递到子查询中

php - Eloquent 中的多个数据库连接与 slim

php - 使用单个表单 Laravel 将数据添加到多个表

javascript - jquery.min.js :2 Uncaught TypeError: Cannot read property 'replace' of undefined (javascript)(laravel)

php - 形式上加一到多 - Backpack laravel