gpt4 book ai didi

php - 在什么情况下laravel的eloquent collection save()会出错呢?

转载 作者:可可西里 更新时间:2023-11-01 13:24:16 25 4
gpt4 key购买 nike

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

    // create or update some data

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

throw new Exception('Model could not be saved');

我不喜欢用 if 语句包围 save() 来检查模型是否已保存。如果它抛出异常,我很乐意将它包装在 try..catch block 中,例如,

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

那么,laravel 口若悬河的集合save() 会不会出错呢?或者,我只是想多了?

最佳答案

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

Illuminate\Database\QueryException: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails ...

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

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

  2. 扩展而不是重写方法,将方法命名为 saveOrFail()

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

关于php - 在什么情况下laravel的eloquent collection save()会出错呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26037629/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com