如何检查laravel eloquent更新方法是否成功

4 laravel

我看到 laravel eloquent update 方法返回更新行的计数。

所以如果没有要更新的行,它会返回 0,这使得 if 语句中的内容不明确。

那么你们如何检查更新是否正确执行。

Bog*_*dan 5

我猜你指的是查询生成器的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
}
Run Code Online (Sandbox Code Playgroud)