简体   繁体   中英

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?

Why don't you set up your models like it is suggested in the documentation here :

So your models would look something like this:

User Model

public function departments()
{
    return $this->belongsToMany('path\to\your\model\Department');
}

Department Model

public function users()
{
    return $this->belongsToMany(path\to\your\model\User);
}

Eloquent will join the two related model names in alphabetical order.So you don't need extra arguments when defining your relationship and Laravel also by default, makes model keys present on the pivot object. And then you can do something like this:

$department = path\to\your\model\Department::find(1);

foreach ($department->users as $user) {
    echo $user;
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM