How to check if a record exists in a database before inserting

I want to check if a book exists in a database before i insert the same book to avoid duplication.

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', $checkmodel->book_id]);

    }

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

What’s the problem with the code you’ve posted?

When I face duplication problem where one of column values should’t be duplicated I use rules to do that;

public function rules() {
    return [
          [['book_id'], 'unique'],
    ];
}

It’s easier way to manage simple duplicates. Maybe It’s useful for You aswell. It will return message with duplicate info in form of an error.

the code does not set the flash i need it to, can you note any problem?

Try using success instead of Success.

I tried, it didn’t work

Are you missing all flash messages or just some of them?

Am missing for this view

The code you’ve posted doesn’t look wrong. It is likely an issue elsewhere. I’d check view.

It’s just example or?

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

By default you’re looking here string “book_id” in book_id column?

And to check is record exist better is use count() or exist() istead od one().

can we connect with skype so that you can get me well? skype:Joshua.kittot

I have tried exists() also. it doesn’t work.