Answer the question
In order to leave comments, you need to log in
How to correctly update records from a table?
Trying to edit a post
$postData = $this->request->post();
$model->load($postData);
$model->validate();
$model->save();
Why with $model->save(); there is an attempt to insert a new record, and not update an existing one, because it is already loaded from the POST? id(primary key) is there.
Answer the question
In order to leave comments, you need to log in
When you load data into a model from a post, they are simply loaded into attributes and that's it, no search among already created models by default occurs. Accordingly, if you want to edit the model, you must:
1. First find it
2. Then load the data from the post
3. Save
Apparently you are creating a new object instance.
public function actionUpdate($id)
{
$model = Model::findOne($id);
if ($model === null) {
//exception
}
$model->load(Yii::$app->request->post());
$model->save();
return $this->render ....
}
if so:
$model = new SomeModel();
$model->save();
$model = SomeModel::find()->one();
$model->save();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question