繁体   English   中英

在发布到 yii2 中的数据库之前检查数据是否存在

[英]Check if data exists before posting into the database in yii2

我正在尝试检查一本书是否已经在数据库中以避免重复。 下面的代码会针对现有的和不在数据库中的代码弹出。

public function actionCreate($book_id = 'book_id')
{
$checkmodel = Books::find()->where(['book_id' => $book_id])->one();

if ($checkmodel) {
    Yii::$app->session->setFlash('error', 'The book has been borrowed, Please look for another one.');

    return $this->redirect(Yii::$app->request->referrer);
}

$model = new Books();

if ($model->load(Yii::$app->request->post()) && $checkmodel->save()) {
    Yii::$app->session->setFlash('Success','You have successfully borrowed the book');
    return $this->redirect(['view' => 'book_id', $model->book_id]);

}

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

}

您可以避免检查在 model 中添加正确的验证规则,因为您应该尝试检查不是 null $checkmodel

    if (!is_null($checkmodel) {
        Yii::$app->session->setFlash('error', 'The book has been borrowed, Please look for another one.');

        return $this->redirect(Yii::$app->request->referrer);
    }

https: //www.yiiframework.com/doc/api/2.0/yii-validators-uniquevalidator https: //www.yiiframework.com/doc/guide/2.0/en/input-validation

public function actionCreate($book_id = 'book_id')
{   
    $model = new Books();
    // check if post request
    if ( $model->load(Yii::$app->request->post()) ) {
        // check if book_id exists in table
        if ( ! Books::find()->where(['book_id' => $book_id])->one() ) {
            // save new record to model
            if ( ! $model->save() ) {
                // set error message and redirect to 'create' page
                Yii::$app->session->setFlash('Error','There was some error in processing your request');
                return $this->redirect(Yii::$app->request->referrer);
            } 
            // if model is saved successfully, redirect to 'view' page
            Yii::$app->session->setFlash('Success','You have successfully borrowed the book');
            return $this->redirect(['view', 'book_id' => $model->book_id]);
        } else {
            // if book_id exist in table, show error message
            Yii::$app->session->setFlash('error', 'The book has been borrowed, Please look for another one.');
            return $this->redirect(Yii::$app->request->referrer);
        }
    }

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

在 if 语句中检查“假”条件总是比检查真更好。 帮助我们编写更简洁的代码。 在您的重定向到查看语句中也存在语法错误

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM