首页 > 解决方案 > hasOneThrough 和 hasManyThrough 在 Eloquent 中不起作用

问题描述

我有以下表格

users          userdatas        workdays
---------      -----------      --------
id             id               id
               user_id
               workday_id

我想获取用户的工作日(然后获取所有具有指定工作日的用户,但一次一步)。我尝试了几种变体,但它不起作用。我相信问题可能是工作日没有参考userdatas

在用户模型中:

public function workday() {
    return $this->hasOneThrough('App\Workday', 'App\Userdata');
}

我还定义了以下内容:

Userdata

public function workday() {
    return $this->hasOne('App\Workday');
}

Workday

public function userdatas() {
    return $this->belongsToMany('App\Userdata');
}

是否必须在中定义反向关系Workday?有什么技巧可以让它工作吗?

谢谢!

标签: laraveleloquenthas-one-through

解决方案


你遵循错误的关系。根据您的数据库表设计,它应该是多对多关系(belongsToMany)。

在用户模型中传递如下关系。

public function workdays() {
    return $this->belongsToMany('App\Workday', 'userdatas','user_id','workday_id');
}

推荐阅读