Yii2:如何在model-> save()之后执行sql查询

时间:2016-04-14 15:05:05

标签: php mysql yii yii2

    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,
                ]);
            }

        }

我需要在model-> save();

之后执行查询\Yii::$app->db->createCommand("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '$model->room_type' ")->execute();

同样的查询在actionupdate()中工作但在actioncreate()中没有, 行为可能吗?

1 个答案:

答案 0 :(得分:1)

您可以覆盖ActiveRecord的afterSave方法或直接在db

上创建触发器

文档: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();

}