我有以下三个表:Class
,Schedules
和Attendance
。
教授选择学生错过的时间表来记录出勤率。为此,他使用的复选框将返回student_id
,class_id
和schedule_id
。每当教授改变出勤率时,都需要更改schedule_id
。
问题在于他没有出席会议("这名学生在这个时间表中错过了我的课程" )但是想要在之后将其还原(&#34 ;这个学生在这个时间表中没有错过课程,我的错误" ),教授将删除出勤率,schedule_id
需要被删除。
因此,如果我在updateOrCreate
方法中没有对请求设置schedule_id,我需要一种方法来找到放弃外键的方法。
出席会议的控制人员:
foreach ($attendances as $f){
$class->attendances()->updateOrCreate(
[
'class_id' => $f['class_id'],
'student_id' => $f['student_id'],
],[ [
'schedule_id' => $f,
]
);
}
班级模特:
public function attendances()
{
return $this->hasMany(Attendance::class);
}
关系:
Class->hasMany->attendances(). Attendances->hasMany->schedules.
答案 0 :(得分:0)
通过选中复选框的值,您可以为此用例设置所需的操作。
if (Request::get('mycheckbox')) {
// got schedule_id
// Insert/Update Record
} else {
// Don't have schedule_id
// Delete Record
Schedules::destroy($id);
}
如果您只想通过删除请求中未列出的所有ID来更新多对多表,请使用sync
。文档链接:https://laravel.com/docs/5.5/eloquent-relationships#inserting-and-updating-related-models - >部分同步关联
您也可以使用sync方法构建多对多关联。 sync方法接受要放在中间表上的ID数组。将从中间表中删除不在给定数组中的任何ID。因此,在此操作完成后,只有给定数组中的ID将存在于中间表中。