5 years ago

Is there a better way to set multiple pivot values at once?

Posted 5 years ago by austenc

I have 3 tables: students, instructors, and instructor_student. The idea is that an instructor can be set as the 'current owner' of a student, and there can only be one 'owner' at a given time (a student might have many instructor/owners over time though). I'm using an boolean pivot field called active to determine which one is the currently active instructor. Here's my pivot table structure:


So, to update the current instructor/owner for a given student, I'm doing something like this:

$student = Student::find($id);
DB::table('instructor_student')->where('student_id', '=', $this->id)
    ->update(['active' => false]);
$student->instructors()->attach($instructorId, ['active' => true]);

Problem is, what if I want to update / set the current instructor for many students at once? Say I have a list of student ID's that I want to set the current instructor for... is my best option to do a whereIn to set any currently active to false, and then call sync to set the new active instructor for all the students?

Just want to make sure I'm thinking about this correctly. Thoughts?

Please sign in or create an account to participate in this conversation.