Reputation: 478
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
Upvotes: 0
Views: 9869
Reputation: 478
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
Upvotes: 1
Reputation: 133360
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
Upvotes: 6
Reputation: 96
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();
Upvotes: 2