laravel 如何检查laravel eloquent更新方法是否成功
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/50512433/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check that laravel eloquent update method is success
提问by volcaniCody
I see that laravel eloquent update method returns the count of updated lines.
我看到 laravel eloquent update 方法返回更新行的计数。
so if there were no line to update, it return 0 which makes it ambiguous in if statement.
所以如果没有要更新的行,它会返回 0,这使得 if 语句中的内容不明确。
so how you guys do you check if update is performed without errors.
那么你们如何检查更新是否正确执行。
采纳答案by Bogdan
I'm guessing you're referring to the Query Builder's update
method (which returns the updated count) and not the Eloquent one (which returns a Boolean value). If that's the case, then the way to go is to use a try ... catch
block and handle any instances of QueryException
:
我猜你指的是 Query Builder 的update
方法(它返回更新的计数)而不是 Eloquent 的方法(它返回一个布尔值)。如果是这种情况,那么要走的路是使用try ... catch
块并处理以下任何实例QueryException
:
try {
// Get the updated rows count here. Keep in mind that zero is a
// valid value (not failure) if there were no updates needed
$count = DB::table('users')->update([
'active' => true
]);
} catch (\Illuminate\Database\QueryException $e) {
// Do whatever you need if the query failed to execute
}
回答by Saurabh
Something like this:
像这样的东西:
$updated = DB::table('tablename')
->where('id', $id)
->update([
'name' => $name,
]);
if($updated) {
// returns true
}
else {
// returns false
}