douzai9405 2016-04-14 15:05
浏览 944

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

    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(); after the model->save();

same query working in actionupdate() but not in actioncreate(), Is it possible with behaviours?

  • 写回答

1条回答 默认 最新

  • dragon8837 2016-04-14 15:26
    关注

    You could override afterSave method of ActiveRecord or create a trigger directly on db

    Documentation: 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();
    
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器