laravel - 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
?有什么技巧可以让它工作吗?
谢谢!
解决方案
你遵循错误的关系。根据您的数据库表设计,它应该是多对多关系(belongsToMany
)。
在用户模型中传递如下关系。
public function workdays() {
return $this->belongsToMany('App\Workday', 'userdatas','user_id','workday_id');
}
推荐阅读
- javascript - 如何使用 reduce 从深层嵌套数组对象中检索值
- apache-spark - 加入 Spark Databricks 上的数据爆炸
- linux - 即使安装了 http-server 和 angular-http-server,得到“bash: http-server: command not found”
- python - 根据浮点数绘制日期时间对象
- r - 在 Fisher 检验 R 中将优势比和 CI 与 p 值相结合
- javascript - 如果用户未登录反应如何隐藏导航
- java - 上传您自己的头像
- python - Python Dataframe:使用 astype 更改列类型失败
- json - 使用 ClickHouse 使用来自 Kafka 的嵌套 JSON 消息
- sql - T-SQL 在用作默认值的函数中使用列名作为参数