我正在尝试检查数据库中是否已经有一本书,以避免重复。下面的代码针对现有数据库和不在数据库中的代码弹出。
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,
]);
}
您可以避免在模型中添加适当的验证规则的检查无论如何,对于您应该保护的代码,请尝试检查是否不为空$ 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-uniquevalidatorhttps://www.yiiframework.com/doc/guide/2.0/en/input-validation