When updating a pivot table model to be populated from a checkBoxList I use to simply do the following:
// First delete all related pivot records as the user could have unchecked some
// previously checked items.
PivotTableModel::deleteAll(['pivot_id' => $model->id]);
// Update the pivot records by reinserting the old ones and adding the new.
if (!empty($model->pivot)) { // $model->pivot populated by a checkBoxList
foreach($model->pivot as $checkbox) {
$pivotRecord = new PivotTableModel();
$pivotRecord->pivot_id = $model->id;
$pivotRecord->related_id = $checkbox;
$pivorRecord->save();
}
}
If you don’t need to preserve existing choices it is easiest to wipe it clean and save. Good tip on the batch insert, that would save quite a few extra queries.
This example could be improved by wrapping the entire thing in a transaction. I’m guessing you find it undesirable for your update to fail after the original choices are deleted, and would rather revert to original state.