Usman Khan
Usman Khan

Reputation: 56

Laravel Eloquent Relationship get not assigned data

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

Upvotes: 0

Views: 82

Answers (2)

Usman Khan
Usman Khan

Reputation: 56

I have did this and it worked...

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

    })->get();

Upvotes: 0

JS TECH
JS TECH

Reputation: 1583

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

Upvotes: 1

Related Questions