skip to Main Content

Her is my DB Structure
DB Design

I want to get 2 things.

  1. Allocated Departments to a user

  2. Departments not allocated to the user
    I have achived first one through hasMany() relationship in AllocatedDepartment Model

      public function departments(){
          return $this->hasMany(Department::class, 'id', 'department_id');
      }
    

I am not understanding how to get departments which are not allocated to the user.

EDITED:
I think you didn’t get my question.
Let say I have user A and departments X Y Z
X is assigned to A

Now I want to get list of departments assigned to A Output = X

and get list of departments assigned to A Output = Y Z

2

Answers


  1. Chosen as BEST ANSWER

    I have did this and it worked...

    $departments = Department::whereDoesntHave('users', function (Builder $query) use ($user){
            $query->where('user_id', '=', $user->id);
    
        })->get();
    

  2. I think you are looking for Many-To-Many Relationships and Querying Relationship Absence.

    User model

    public function departments()
    {
        return $this->belongsToMany(Department::class, 'allocated_departments', 'user_id', 'department_id');
    }
    

    Department model

    public function users()
    {
        return $this->belongsToMany(User::class, 'allocated_departments', 'department_id', 'user_id');
    }
    

    Now,

    $departments = Department::doesntHave('users')->get();
    
    // or
    
    $users = User::doesntHave('departments')->get();
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search