Проверьте, существуют ли данные перед публикацией в базе данных в yii2 - PullRequest
0 голосов
/ 28 апреля 2020

Я пытаюсь проверить, есть ли книга в БД, чтобы избежать дублирования. Приведенный ниже код всплывает как для существующего, так и для отсутствующего в базе данных.

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

Ответы [ 2 ]

0 голосов
/ 28 апреля 2020
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, чем в true. Помогает нам писать более чистый код. Также произошла синтаксическая ошибка в вашем перенаправлении для просмотра оператора

0 голосов
/ 28 апреля 2020

Вы могли бы избежать проверки, добавив в вашу модель правильное правило проверки в любом случае для вашего кода, вы должны попробовать проверить, не является ли $ 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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...