i have method to mass update the studentSection table. This method works. But if i mass update multiple records only one record gets save.
Update (latest)
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);
}
Second approach: This works but it does not trigger my observer that outputs message. 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);
}
Here's my relationship
Enrollment Model
public function studentSection()
{
return $this->hasOne('App\Models\Student\Section');
}
StudentSection model
public function enrollment()
{
return $this->belongsTo('App\Models\Enrollment', 'enrollment_id');
}
CodePudding user response:
Third approach
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);