In laravel Many to Many relationship like the one in the Laravel Documentation example. https://laravel.com/docs/9.x/eloquent-relationships#many-to-many

users
    id - integer
    name - string

roles
    id - integer
    name - string

role_user
    user_id - integer
    role_id - integer

In the Users model I have

public function roles()
{
    return $this->belongsToMany(Role::class);
}

In the Roles model I have

public function users()
{
    return $this->belongsToMany(User::class);
}

How can I get all Role that I don't have a relationship to.

I tried thing like

$this->availableRoles = Role::doesntHave('users')->get();

But this give me all the Role that no user at all have

Any hint on this.

推荐答案

If you already have a User instance (I assume that is what $this is?), then you can simply filter the relationship:

$this->availableRoles = Role::whereDoesntHave('users', function ($subQuery) {
  return $subQuery->where('users.id', $this->id);
})->get();

This should return all Role elements, unless that Role has an association with the User ($this, $user, auth()->user(), etc.; adjust as required).

An alternative approach, filter out Role based on existing Roles:

$this->availableRoles = Role::whereNotIn('id', $this->roles->pluck('id'))->get();

This approach get's the roles.id for the User instance.

You can take a look at query efficiency and use the one that works best, but either approach should work fine.

Note: If $this is not a User instance, adjust:

$user = User::find($userId); // or `auth()->user()`, etc.

$availableRoles = Role::whereDoesntHave('users', function ($subQuery) use ($user) {
  return $subQuery->where('users.id', $user->id);
})->get();

// OR

$availableRoles = Role::whereNotIn('id', $user->roles->pluck('id'))->get();

Php相关问答推荐

Msgraph-sdk-php v2如何从返回对象中获取数据?

使用PHP阅读XML提要

在PHP中循环访问多维数组,并按组显示内容

在Laravel中为表添加前缀,以将它们逻辑地分组

当配置的URL为空时禁用Laravel Slack日志(log)记录

FlySystem v3:使用本地适配器时出现问题

根据类别的数量折扣更改WooCommerce购物车商品价格

如何从phpseclib和SFTP获取日志(log)记录?

文本到语音:不考虑音高值

PHP 支持 APNG 文件吗?

订单完成后创建 WooCommerce 促销代码

如何正确判断 PHP 是否已正确配置为使用 DOMDocument?

尽管有use指令,PHP 类在其他文件中仍处于可见状态

PHP 中的curl -F request=@file.xml

如何在自定义消息中包含 WooCommerce 选定的产品变体详细信息

在 PHP 中验证签名

如何使用相同的变量使函数参数对于数组和字符串都是可选的

正则表达式 (php) 匹配单个 [ 或单个 ] 但忽略 [[ ]] 之间的任何内容?

列表不在 GROUP BY 子句中并且包含 X2CRM 中的非聚合列

Laravel 从嵌套数组的第二级获取最后一项