Yii2:无法按 + 1 更新列值 [英] Yii2: not able to update column value by + 1

查看:24
本文介绍了Yii2:无法按 + 1 更新列值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在创建新记录时将列值更新为 + 1 :

公共函数actionCreate(){$model = new CreateBookings();if ($model->load(Yii::$app->request->post())) {Yii::$app->db->createCommand("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '$model->room_type'")->execute();$model->save();返回 $this->redirect(['view', 'id' => $model->id]);} 别的 {返回 $this->render('create', ['模型' =>$模型,]);}}

我做错了什么请指导:)

解决方案

试试这个:

 Yii::$app->db->createCommand("UPDATE room_types SET total_booked=total_booked+1 WHERE room_type = '$model->room_type'")->execute();

公共函数actionCreate(){$model = new CreateBookings();if ($model->load(Yii::$app->request->post())) {$RoomType = new room_types();//房间类型替换为模型名称$RoomType->updateCounters(['total_booked' => 1]);$model->save();返回 $this->redirect(['view', 'id' => $model->id]);} 别的 {返回 $this->render('create', ['模型' =>$模型,]);}}

官方链接

I need to update column value by + 1 when new records get created :

public function actionCreate()
    {
        $model = new CreateBookings();
        if ($model->load(Yii::$app->request->post())) {
            Yii::$app->db->createCommand("UPDATE room_types SET total_booked = total_booked + 1 WHERE room_type = '$model->room_type' ")->execute();
            $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
            } else {
                 return $this->render('create', [
                 'model' => $model,
                 ]);
            }
    }

What am I doing wrong please guide :)

解决方案

Try this:

 Yii::$app->db->createCommand("UPDATE room_types SET total_booked=total_booked+1 WHERE room_type = '$model->room_type' ")->execute();

OR

public function actionCreate()
    {
        $model = new CreateBookings();
        if ($model->load(Yii::$app->request->post())) {

    $RoomType = new room_types(); // room type replace with model name
    $RoomType->updateCounters(['total_booked' => 1]);

      $model->save();
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

Official link

这篇关于Yii2:无法按 + 1 更新列值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆