Yii2:如何在模型创建之前检查条件

时间:2016-04-17 18:45:41

标签: php yii yii2

public function actionCreate()
{
    $model          = new Bookings();
    $temp           = new RoomTypes();
    $roomtype = $model->room_type;
    $checkRoomModel = RoomTypes::find()->where(['room_type' => $room_type])->one();

    $totalremain = $temp->total_remain;
    if ($model->load(Yii::$app->request->post())) 
    {
        if ($checkRoomModel->totalremain > 0) 
        {
                $imageName   = $model->first_name;
                $mobile      = $model->primary_mobile;
                $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();
                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_remain = total_remain - 1   WHERE room_type = '$model->room_type'")->execute();
            } else {
                echo "This room Types are full ";
            }

            return $this->redirect(['view', 'id' => $model->id]);
        }

    } else {
        return $this->render('create', [
            'model' => $model,
            'temp'  => $temp,
        ]);
    }
}

在数据库中有列total_remain和total_booked,我需要在actioncreate()之前验证$ model-> room_type的total_remain不等于零

怎么做?

2 个答案:

答案 0 :(得分:1)

如果您想在行动前使用行动

之前运行它
    public function beforeAction($event)
    {
        if (parent::beforeAction($action)) {
                if ($this->action->id == 'create') {
                   $roomModel = RoomTypes::find()->where( [   'room_type' => $room_type ])->one();
                   if($roomModel->totalremain) > 0) 
                   {
                        return false;
                   }
                   else
                   {
                        return true;
                   }
                }
        }
        else
        {
            return false;
        }
    }

答案 1 :(得分:0)

最简单的方法是选择相关模型,然后将代码驱动到正确的活动

public function actionCreate()
   {
       $model = new Bookings();
       $temp  = new RoomTypes();
       $checkRoomModel = RoomTypes::find()->where( [   'room_type' => $room_type ])->one();
       if ( $checkRooModel->totalremain) > 0 {
               ....