Home > database >  Laravel Eloquent Relationship get not assigned data
Laravel Eloquent Relationship get not assigned data

Time:10-18

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

CodePudding user response:

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();

CodePudding user response:

I have did this and it worked...

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

    })->get();
  • Related