We have two models “Foo” and “Bar”, as in the picture below (one Foo can have many bars).

Let's say that we want to update the model Foowith values from $_POST. Due to the relationship Foowith, Barwe also want to update the model Barwith values from the same $_POST. Foothe update process is the same as usual (i.e., it loads the model Foofrom the database using foo ID, then loads the model $_POSTinto Fooand saves the model). But it Foocan have many Bars, so we delete all the records from the table table with $fooIdand create new records for the table table from $_POST.
, , Foo // . , foo - "foo", - "bar1", "bar2" "bar3". foo "fooChanged" "bar1" "bar10" "bar3". : "bar2" . Foo, foo ( "foo" "fooChanged" ) . Bar . -, , $fooId, batchInsert (. ).
:
public function actionUpdateFoo($fooId = null)
{
$foo = Foo::findOne($fooId);
$foo->load(Yii::$app->request->post());
$transaction = Yii::$app->db->beginTransaction();
if ($foo->save() && Bar::deleteAll(['foo_id' => $fooId]) && Bar::create($fooId, Yii::$app->request->post())) {
$transaction->commit();
} else {
$transaction->rollBack();
}
return $this->render('foo', [
'foo' => $foo,
]);
}
:
public static function create($fooId, $post)
{
$array = [];
foreach ($post['Bar'] as $item) {
array_push($array, [
'foo_id' => $fooId,
'name' => $item['name'],
]);
}
return Yii::$app->db->createCommand()->batchInsert(self::tableName(), ['foo_id', 'name'], $array)->execute();
}
, , , Bar . , , , , , . ( , Bar , "bar2" ).
, ( )?