Yii-2 how to update a record on basis of id

9.4k Views Asked by At

I want to update my table/model. The scenario is, I have a 'status' column, I want to SET this column to a value then update the model based on the id. I want to do something like update statement.

Update 'table' SET status = 'status value' where id = 'myid'

My action controller look like

$model = $this->findModel($id);
$ogp_id = $model->id;
$status = $model->status;

I have searched for it but couldn't find a solution

Any help would be highly appreciated

3

There are 3 best solutions below

1
Moeez On BEST ANSWER

This Works for me

I added a function

 protected function findModel($id)
{
    if (($model = Ogpheader::findOne($id)) !== null) {
        return $model;
    } else {
        throw new NotFoundHttpException('The requested page does not exist.');
    }
}

Then access it inside the controller

$model = $this->findModel($id);
$ogp_id = $model->id;

Then while saving my model I have done the following

if($m->save())
{
   $model->status = Ogpheader::$status_titles[1];
   $model->update();
   //my other code
}

This has updated my table and set the column as required

1
Sujat On

Try like this,

  $model =Table::find($id);
    $model->status = 'Active';
    $model->save();

also use Create command can be used directly as follows :

Yii::$app->db->createCommand("UPDATE table SET status=:status WHERE id=:id")
->bindValue(':id', your_id)
->execute();
1
ScaisEdge On

for retrive the $id related model You can use findOne($id) if id is the primary key

$model =YourModel::findOne($id);
$model->status = 'Active';
$model->save();

or find()->Where()->one() in general cases

$model =YourModel::find()-where(['id'=>$id])->one();
$model->status = 'Active';
$model->save();

if your validation rules fail you can try using $model->save(false); if in this case e row is updated thin mean that some of your data don't respect validation rules .. and you should check for this