首页 > 解决方案 > 如何在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,
    ]);
}

标签: phpyii2yii2-advanced-app

解决方案


要获取模型验证错误,您可以调用$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
}

详细信息可以在Class yii\base\Model #validate的官方文档中找到


推荐阅读