在什么情况下,laravel的雄辩集合save()会出错?

use*_*288 6 php laravel

我想知道elqouent save()可能抛出的错误或异常.在laravel中,我在保存或更新模型时一直这样做.

    // create or update some data

    if($model->save()){
        // continue
        return true;
    }

    throw new Exception('Model could not be saved');
Run Code Online (Sandbox Code Playgroud)

我不喜欢save()if语句来检查是否保存了模型.如果它抛出一个异常然后,我很想把它包装成try..catch块,就像,

    try{    
        // create or update some data
        $model->save()
        // continue
        return true;
    catch(SomeException $e){
        throw new Exception('Model could not be saved');
    }
Run Code Online (Sandbox Code Playgroud)

那么,laravel的雄辩收藏save()会出错吗?或者,我只是在思考它?

Ton*_*ony 5

我遇到的唯一例外是当我设置外键约束并在我的代码中(或由用户)破坏它们时,这将抛出一个 QueryException 形式如下:

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ...
Run Code Online (Sandbox Code Playgroud)

如果要显式抛出异常,我可以想到2.5种方法:

  1. 从基本模型扩展并覆盖该save()方法,以便如果它返回 false,它会抛出自己的异常供您捕获。

  2. 扩展而不是覆盖,命名方法saveOrFail()

  3. 使用此库的saveOrFail()方法(与#1 的作用相同)但已抽象化(https://github.com/dwightwatson/validating)。