Properly updating models with checkBoxList


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;




Someone to know a cleaner way of doing this?

Thanks in advance

I dont know a ‘cleaner’ way but I use this another approach to run fewer SQLs against the db:


                	->batchInsert('junction_table', [



                	], [[1,2], [5,3], [5,4], [1,4]...])


AFAIK, this way, only one command is executed against the db server (inserting all records once a time) instead of one for each model.

Hope it helps.

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.

Nice tip. Thanks!

Transactions… Good suggestion. :D