/** * @return \yii\db\ActiveQuery */ public function getTable1s() { return $this->hasMany(Table1::className(), ['order_id' => 'id']); }
public function actionUpdate($id) { $modelorder = $this->findModel($id); $modelsorders = $modelorder->table1s; if ($modelorder->load(Yii::$app->request->post())) { $oldIDs = ArrayHelper::map($modelsorders, 'id', 'id'); $modelsorders = Model::createMultiple(Table1::classname(), $modelsorders); Model::loadMultiple($modelsorders, Yii::$app->request->post()); $deletedIDs = array_diff($oldIDs, array_filter(ArrayHelper::map($modelsorders, 'id', 'id'))); // ajax validation if (Yii::$app->request->isAjax) { Yii::$app->response->format = Response::FORMAT_JSON; return ArrayHelper::merge(ActiveForm::validateMultiple($modelsorders), ActiveForm::validate($modelorder)); } // validate all models $valid = $modelorder->validate(); $valid = Model::validateMultiple($modelsorders) && $valid; if ($valid) { $transaction = \Yii::$app->db->beginTransaction(); try { if ($flag = $modelorder->save(false)) { if (!empty($deletedIDs)) { Table1::deleteAll(['id' => $deletedIDs]); } foreach ($modelsorders as $modelTable1) { $modelTable1->order_id = $modelorder->id; if (!($flag = $modelTable1->save(false))) { $transaction->rollBack(); break; } } } if ($flag) { $transaction->commit(); return $this->redirect(['update', 'id' => $modelorder->id]); } } catch (Exception $e) { $transaction->rollBack(); } } } return $this->render('update', ['modelorder' => $modelorder, 'modelsorders' => empty($modelsorders) ? [new Table1()] : $modelsorders]); }