Search code examples
phpmysqllaraveleloquentmodels

Laravel belongsToMany not returning results


I have the following schema set up:

users:

  • id

departments:

  • id

department_user:

  • id
  • department_id
  • user_id

I also have the following relationships set up:

User Model

public function departments()
{
    return $this->belongsToMany('App\Resources\Eloquent\Models\Department', 'department_users');
}

Department Model

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

For some reason, when I am trying to access through the user model $user->departments, it doesn't work - but $department->users does.

Outputting the eloquent query is as follows:

select `departments`.*, `department_users`.`user_id` as `pivot_user_id`, `department_users`.`department_id` as `pivot_department_id` from `departments` inner join `department_users` on `departments`.`id` = `department_users`.`department_id` where `department_users`.`user_id` is null

I can't seem to figure out why it is looking to see if department_users.user_id is null, when it should be looking for the user's id.

Any ideas?


Solution

  • For some reason, if I make the relationship the following - it works.

     return $this->belongsToMany(Department::class, 'department_users')->orWhere('department_users.user_id', $this->id);
    

    If anyone knows why, please let me know