You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel中如何筛选出不属于ID为6的Group的所有User?

问题需求

筛选出所有不属于ID为6的Group的用户。

数据库表结构

1. users表

idname
Cell 1Cell 2
Cell 3Cell 4

2. group表

idname
Cell 1Cell 2
Cell 3Cell 4

3. group_users关联表

iduser_idgroup_id
Cell 1Cell 2Cell 4
Cell 3Cell 4Cell 6

模型关联代码

Group模型的users关联

// 群组的所有成员用户
public function users()
{
    return $this->belongsToMany(User::class);
}

User模型的groups关联

// 用户所属的所有群组
public function groups()
{
    return $this->belongsToMany(Group::class);
}

尝试的代码及问题

我尝试了以下代码,但无法将获取到的$users转换为ID数组,请求解决:

public function show(Group $group)
{
    //获取该群组的所有成员
    $users = $group->users()->get()

    return Inertia::render('Clients/Show', [
            'users' => Group::whereNotIn('id', $users)->get()
    ]);
}

解决方案

你的代码存在两个核心问题:

  1. 目标是筛选用户而非群组,应该调用User::whereNotIn而非Group::whereNotIn
  2. 直接传入Eloquent集合到whereNotIn会报错,需要提取集合中的用户ID数组

修正代码(基础版)

public function show(Group $group)
{
    // 获取该群组所有成员的ID数组
    $groupUserIds = $group->users()->pluck('id');

    // 筛选出不在该群组的所有用户
    $usersNotInGroup = User::whereNotIn('id', $groupUserIds)->get();

    return Inertia::render('Clients/Show', [
        'users' => $usersNotInGroup
    ]);
}

优化方案(高性能版)

如果希望减少数据库查询次数,可使用whereDoesntHave直接查询无关联的用户:

public function show(Group $group)
{
    $usersNotInGroup = User::whereDoesntHave('groups', function ($query) use ($group) {
        $query->where('groups.id', $group->id);
    })->get();

    return Inertia::render('Clients/Show', [
        'users' => $usersNotInGroup
    ]);
}

内容的提问来源于stack exchange,提问作者Lindani Dube

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 01:10:18