简体   繁体   English

Laravel属于ToMany未返回结果

[英]Laravel belongsToMany not returning results

I have the following schema set up: 我设置了以下架构:

users: 用户:

  • id ID

departments: 部门:

  • id ID

department_user: department_user:

  • id ID
  • department_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. 由于某些原因,当我尝试通过用户模型$user->departments ,它不起作用-但是$department->users可以。

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. 我似乎无法弄清楚为什么它应该在查找用户ID时才查看department_users.user_id是否为null。

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. Eloquent会按字母顺序将两个相关的模型名称连接在一起。因此,在定义关系时不需要额外的参数,并且默认情况下,Laravel也使模型键出现在数据透视对象上。 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 如果有人知道为什么,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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