Search code examples
phpyii2updatemodel

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


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


Solution

  • 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