M
M
McMike2016-12-12 15:24:56
Yii
McMike, 2016-12-12 15:24:56

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

3 answer(s)
M
Maxim Fedorov, 2016-12-12
@McMike

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

A
Andrew, 2016-12-12
@mhthnz

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 ....
}

M
Maxim Timofeev, 2016-12-12
@webinar

if so:

$model = new SomeModel();
$model->save();

we have a new record, since a new model instance has been created, empty, without an id and $model->isNewRecord returns true
and if so:
$model = SomeModel::find()->one();
$model->save();

then this model has an id and the $model->isNewRecord method returns false and therefore the data with a certain id will be updated

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question