Laravel DB update
函数在查询失败或行未受影响时返回 0,因为更新值相同。
如何检查查询失败是因为错误还是因为行未受影响?在下面的代码中,如果值相同,它将返回并且不会在 Controller 中运行下一组代码。
$query = DB::table('users')
->where('id', '=' , $requestdata['user_id'] )
->update([
'first_name' => $requestdata['user_fname'],
'last_name' => $requestdata['user_lname'],
]);
if ( !$query ) {
return ['error' => 'error update user'];
}
最佳答案
更新查询返回受更新查询影响的行数。
$returnValue = DB::table('users')
->where('id', '=', $data['user_id'] )
->update([
'first_name' => $data['user_fname'],
'last_name' => $data['user_lname'],
]);
所以上面将返回更新的记录数。 0
表示没有记录被更新。
但是,对于您来说,即使返回 0
也可能并不意味着错误,因为它只是意味着没有更新的记录。因此,如果您尝试使用实际上已经包含的详细信息更新用户的姓名和姓氏,查询将返回 0
。
有用的旁注,使用 php artisan tinker
,即。
>>> $retval = DB::table('users')->where('id', 1)->update(['first_name' => 'Testing']);
=> 1
再次运行相同的查询,您会注意到它返回 0
个受影响的行,因为名称已经是 Testing
>>> $retval = DB::table('users')->where('id', 1)->update(['first_name' => 'Testing']);
=> 0
更新补充:
因此,对您而言,最好首先检查用户是否存在 User::findOrFail($id)
或仅检查 User::find($ id)
,然后如果用户存在,则对返回的 $user
进行条件更新。它更明确,因为更新为不存在的用户返回相同的 0
,如果用户已经详细说明您尝试将其设置为的位置。
关于database - Laravel DB::update 只返回 0 或 1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38551397/