【问题标题】:I want to select all Users which are not members of a certain Group我想选择不是某个组成员的所有用户
【发布时间】:2022-11-11 01:20:24
【问题描述】:

我的桌子

  1. 用户
    id name
    Cell 1 Cell 2
    Cell 3 Cell 4
    id name
    Cell 1 Cell 2
    Cell 3 Cell 4
    1. group_users
    id user_id group_id
    Cell 1 Cell 2 Cell 4
    Cell 3 Cell 4 Cell 6
    // All users which are members of group
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
    
    // All groups user belong to
    public function groups()
    {
        return $this->belongsToMany(Group::class);
    }
    

    这就是我试图做的。我认为问题在于我必须使 $users 成为一个已获取的 id 数组,而我无法做到这一点。请帮忙

    public function show(Group $group)
    {
        //Fetching all members of the group
        $users = $group->users()->get()
    
        return Inertia::render('Clients/Show', [
                'users' => Group::whereNotIn('id', $users)->get()
        ]);
    }
    

【问题讨论】:

    标签: php laravel eloquent-relationship


    【解决方案1】:

    如果要选择没有关系的用户,可以使用whereDoesntHave

    $users = User
        ::whereDoesntHave('groups', fn($query) => $query->where('id', 1))
        ->get();
    

    在这种情况下,我正在查询所有没有链接名为“somegroupname”的组的用户。

    【讨论】:

    • 我实际上想查询那些与 group id=1 没有关系的人
    • 好的,答案已更改
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-02-05
    • 2023-02-08
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 2016-10-24
    相关资源
    最近更新 更多