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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:44:51  来源:igfitidea点击:

How to check that laravel eloquent update method is success

laravel

提问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 updatemethod (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 ... catchblock 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
}