【发布时间】:2019-11-14 15:41:47
【问题描述】:
我目前处于多对多关系中,其中一个表最多有四个外键
user_id | education_id | course_id | created_by
在哪里
user_id 和 added_by 在 users 表上引用 id。
education_id 在education 表上引用id。
course_id 在课程表上引用 id。
对于api,我想知道处理此问题以提高性能的最佳方法。到目前为止,我能够添加数据,但挑战是从相关表中检索数据。
以下是模型。
//User Class
public function education(){
return $this->belongsToMany(Education::class, 'education_user', 'user_id', 'education_id')
->withPivot('created_by', 'course_id', 'institution', 'obtained')
->withTimestamps();
}
//Education Class
public function user(){
return $this->belongsToMany(User::class, 'user_id')->withTimestamps();
}
public function courses(){
return $this->belongsTo(Course::class, 'course_id');
}
//Course Class
public function education(){
return $this->belongsTo(Education::class, )->withTimestamps();
}
public function user(){
return $this->belongsTo(User::class, )->withTimestamps();
}
从我的控制器,我有
public function show($id)
{
$user = User::findOrFail($id);
return EducationUserResource::collection($user->education()->with(['courses'])->get());
}
返回以下数据
{
"data": [
{
"data": {
"education_id": 4,
"name": "BSc",
"last_updated": "7 hours ago",
"course_id": 106,
"course": '',//How can I get the name of the course where id on courses == 106 here
"pivot": {
"user_id": 26,
"education_id": 4,
"created_by": 9,
"creator" : '', //How can I get the name of the user who created this resource here
"course_id": 106,
"institution": "Rivers State University",
"obtained": 2017,
"created_at": "2019-11-14 08:18:05",
"updated_at": "2019-11-14 08:18:05"
}
}
}
]
}
这是我的资源
public function toArray($request)
{
return [
'data' => [
'education_id' => $this->id,
'name' => $this->name,
'last_updated'=> $this->whenPivotLoaded('education_user', function () {
return $this->pivot->updated_at->diffForHumans();
}),
'course_id' => $this->whenPivotLoaded('education_user', function () {
return $this->pivot->course_id;
}),
'course' => $this->whenLoaded('courses'),
'pivot'=> $this->whenLoaded('pivot')
]
];
}
谢谢大家。
【问题讨论】:
-
So far I'm able to add data but the challenge is retrieving data from related tables.你能再解释一下吗? -
我可以将记录附加到关系中。我希望能够从
courses表中查看课程以及从users表中创建记录的人