我有方法批量更新 studentSection 表。這種方法有效。但是,如果我批量更新多條記錄,則只會保存一條記錄。
更新(最新)
public function setStudentsSection(Request $request)
{
$enrollments = Enrollment::whereIn('student_id', $request->students)->where('session_id', $request->session_id)->get();
$program_section = ProgramSection::withCount('students')->find($request->program_section_id);
if(($program_section->students_count count($enrollments)) <= $program_section->max_students) {
$data = [];
foreach($enrollments as $enrollment) {
$data[] = [
'student_id' => $enrollment->student_id,
'enrollment_id' => $enrollment->id,
'section_id' => $request->program_section_id,
'created_at' => Carbon::now()
];
}
StudentSection::createMany($data);
}
return response()->json(['errors' => ['message' => 'Selected Section is full.']], 405);
}
第二種方法:這可行,但不會觸發我輸出訊息的觀察者。Assigned student to section
public function setStudentsSection(Request $request)
{
$enrollments = Enrollment::whereIn('student_id', $request->students)->where('session_id', $request->session_id)->get();
$program_section = ProgramSection::withCount('students')->find($request->program_section_id);
if(($program_section->students_count count($enrollments)) <= $program_section->max_students) {
$new_student_sections = array();
foreach($enrollments as $enrollment) {
$data = [
'student_id' => $enrollment->student_id,
'enrollment_id' => $enrollment->id,
'section_id' => $request->program_section_id,
'created_at' => Carbon::now()
];
array_push($new_student_sections, $data);
}
return StudentSection::insert($new_student_sections);
}
return response()->json(['errors' => ['message' => 'Selected Section is full.']], 405);
}
這是我的關系
招生模式
public function studentSection()
{
return $this->hasOne('App\Models\Student\Section');
}
StudentSection 模型
public function enrollment()
{
return $this->belongsTo('App\Models\Enrollment', 'enrollment_id');
}
uj5u.com熱心網友回復:
第三種方法
if(($program_section->students_count count($enrollments)) <= $program_section->max_students) {
foreach($enrollments as $enrollment) {
$enrollment->studentSection()->create([
'student_id' => $enrollment->student_id,
'section_id' => $request->program_section_id,
'created_at' => Carbon::now() //optional
]);
}
return response('success');
}
return response()->json(['errors' => ['message' => 'Selected Section is full.']], 405);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/506728.html
標籤:拉拉维尔 雄辩 laravel-8 laravel 模型
