[英]Yii2: How to execute sql query after model->save()
public function actionCreate()
{
$model = new CreateBookings();
if ($model->load(Yii::$app->request->post())) {
$imageName = $model->first_name;
$mobile = $model->primary_mobile;
$type = $model->room_type;
$model->file = UploadedFile::getInstance($model, 'file');
$model->file->saveAs('uploads/id_images/' . $imageName . '_' . $mobile . '.' . $model->file->extension);
//save the path in the db column
$model->id_image = 'uploads/id_images/' . $imageName . '_' . $mobile . '.' . $model->file->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->id]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
I need to execute query \\Yii::$app->db->createCommand("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '$model->room_type' ")->execute();
我需要执行查询
\\Yii::$app->db->createCommand("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '$model->room_type' ")->execute();
after the model->save(); 在model-> save()之后;
same query working in actionupdate() but not in actioncreate(), Is it possible with behaviours? 相同的查询在actionupdate()中起作用,但在actioncreate()中不起作用,行为是否可能?
You could override afterSave
method of ActiveRecord or create a trigger directly on db 您可以覆盖ActiveRecord的
afterSave
方法或直接在db上创建触发器
Documentation: http://www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#afterSave%28%29-detail 文档: http : //www.yiiframework.com/doc-2.0/yii-db-baseactiverecord.html#afterSave%28%29-detail
public function afterSave($insert, $changedAttributes)
{
parent::afterSave($insert, $changedAttributes);
// your code here
Yii::$app->db->createCommand(sprintf("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '%s'", $this->room_type))->execute();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.