Nik*_*ili 5 laravel eloquent laravel-4 laravel-5
终于到了我理解这个概念的时候了,因为我仍然没有得到一些案例。
问题1)什么呢save()回报呢?它总是布尔值还是有时会抛出异常?
问题 2)我没有使用任何事件模型。所以我认为save()任何时候都不会返回false。那么它会返回true还是抛出异常?我对吗?
问题3)如果我有这样的事情:
DB::beginTransaction();
try{
$model1 = new Type();
$model1->test = 'great';
$model1->save();
$model2 = new Type();
$model2->test2 = 'awesome';
$model2->save();
DB::commit();
}catch(Exception $e){
DB::rollBack();
}
Run Code Online (Sandbox Code Playgroud)
是否有可能保存不会发生但它不会抛出异常?我在这些模型中没有任何事件。
问题 4)如果问题 3 的答案是“不,这是不可能的”,那么为什么我需要使用saveOrFail()
我真的很感激,因为我真的找不到任何能深刻解释我所问的东西。
Question 1) save() can indeed throw exceptions. For example, if you create a model with a decimal column, e.g. 'cost', and try to save a string value in that column, both save() and saveOrFail() will throw an exception. Demo:
>>> $item->cost = 'asdas';
>>> $item->save();
Illuminate/Database/QueryException with message 'SQLSTATE[HY000]: General error: 1366 Incorrect decimal value: 'asdas' for column 'cost' at row 1 (SQL: update ...
Run Code Online (Sandbox Code Playgroud)
Question 2) Looking through the source, it looks like save() will only return false when firing either the saving, updating or creating events returns false.
Since you haven't defined any event listeners, theoretically yes, you should only ever receive true or an exception will be thrown.
Question 3) If you're not listening to events then no, it's not possible (at least not probable). The save would only not have happened if there was an exception thrown.
Question 4) Since saveOrFail() just wraps save() in a transaction, its use is to keep the database consistent if any exceptions were raised during the save() function. saveOrFail() ensures that if there were any exceptions raised during save(), the model would not have been saved. save() alone would not be able to guarantee that the model was not modified/saved if an exception was thrown.
Since you're already wrapping your code in a transaction, you don't need to use saveOrFail.
For your use case, the best I can think of is to call save() on all of your models in a single if-expression and to commit the transaction only if the expression is true. That way you can cater for both when save() returns false or when it raises an exception. Like this:
DB::beginTransaction();
try {
$model1 = new Type();
$model1->test = 'great';
$model2 = new Type();
$model2->test2 = 'awesome';
if ($model1->save() && $model2->save()) {
DB::commit();
} else {
DB::rollBack();
}
} catch(Exception $e){
DB::rollBack();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3054 次 |
| 最近记录: |