php - 如何在yii2中检查数据库中的现有记录和setFlash
问题描述
我想看看这本书是否被借了。所以我不希望同一本书被发布两次。至于现在它显示重复错误,我如何在检查其存在后捕获该错误。
public function actionCreate()
{
$model = new Books();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'book_id' => $model->book_id]);
}
return $this->render('create', [
'model' => $model,
]);
}
解决方案
要获取模型验证错误,您可以调用$model->validate()
. 然后,您可以使用$model->getErrors()
. 但是,正如评论中指出的那样,save()
还调用validate()
了,因此您提供的示例应如下所示:
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['view', 'book_id' => $model->book_id]);
} else {
$errors = $model->getErrors();
//Process your errors here
}
推荐阅读
- python - 一个python函数返回它自己的运行时参数的签名
- c# - 如何从所有场景列表中删除活动场景
- javascript - Typscript array.find() 没有按预期工作
- xpath - 如何使用 Xpath 获取标签之间的文本信息?
- google-apps-script - 当第 11 列中的值 = 是时,如何使用 Google 脚本将行移动到另一张工作表
- dataframe - 加入后替换pyspark数据框中的列
- c# - WPF 找不到命名空间
- python - 使用 spycopg2 Python Flask 填充 HTML Select
- reactjs - React-Rnd 一个块在另一个块内
- performance - Pytorch 上 L2 正则化的速度