[英]how to join 3 tables in laravel using eloquent hasmanythrough or hasonethrough
这是我的桌子的样子
部门 | 课程 | 科目 |
---|---|---|
ID | ID | ID |
头 | 部门编号 | course_id |
课程名 | 主题代码 |
在我的模型中,这是我的做法,但似乎不起作用,我不知道为什么:
public function departments()
{
return $this->hasOneThrough(
subjectlist::class,
department::class,
'id',
'course_id',
'id',
'id'
);
}
output 当我尝试使用hasOneThrough
时:
{
"id": 1,
"department_name": "Business",
"head": "John smith",
"email": "smith@gmail.com",
"contact_number": "09300282103",
"created_at": null,
"updated_at": null,
"subject_list": {
"id": 1,
"course_id": 1,
"subject_code": "Math1",
"description": "math test",
"year_type": 1,
"price": "200.00",
"units": "5.00",
"created_at": null,
"updated_at": null,
"laravel_through_key": 1
}
}
我不希望 output 应该是这样的请帮我怎么做:
{
"id": 1,
"department_name": "Business",
"head": "John smith",
"email": "smith@gmail.com",
"contact_number": "09300282103",
"created_at": null,
"updated_at": null,
"subject_list": {
"id": 1,
"course_id": 1,
"subject_code": "Math1",
"description": "math test",
"year_type": 1,
"price": "200.00",
"units": "5.00",
"created_at": null,
"updated_at": null,
"laravel_through_key": 1
},
"department": {
"id": 1,
"department_name": "ComputerScience"
}
}
您的表之间的关系就像学科作为课程课程有一个部门,学科有一个部门通过课程
与您的主题的关系 Model
public function Course() {
return $this->belongsTo(Course::class);
}
public function Department() {
return $this->hasOneThrough(Department::class, Course::class)
}
课程关系 Model
public function Subject() {
return $this->hasMany(Subject::class);
}
public function Department() {
return $this->belongsTo(Department::class);
}
与您部门的关系 Model
public function Course() {
return $this->hasMany(Course::class);
}
有关更多信息,请参阅 laravel eloquent 关系文档https://laravel.com/docs/8.x/eloquent-relationships#has-
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.