#(Many to Many) Display all users that don't belong in this particular Department.

3 messages · Page 1 of 1 (latest)

swift raven
#

I have a page with a list of all Departments. You can navigate to each single department. In the single department page there are shown 2 lists. A list of all members and a list of all non-members.
Using this method:
$members = $department->users()->get();
I can display all members succesfully as I have set the relationships properly in User/Department models.

Now I need to show all the non-members and I use this method:

        { 
            $q->whereNot('department_id', $id);
        })->get();

At first glance this works fine, but a problem occurs:
If we are currently in department_id=2 page and a specific user is a member in department with id=2 but also id=1. The method I used above starts the comparison from the department with the lowest id. So is this user a member of department_id=1? Yes it is. Is this different than current department_id (which is 2). Yes it is? So display this user as a non-member, but actually this user is already a member.

I tried using "doesntExist()" as well but didn't work. How can I resolve this?

slow vapor
#
$nonMembers = User::whereNotIn('id', $departmentMembers->pluck('id'))->get();
#

🤷