Return update() 后收集?
Return Collection after update()?
使用 Raw,如何return 收集更新的行?
例如:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
我期待 dd($updated)
到 return 更新集合行,但它 returned 1.
{{$updated->votes}} should return 123
事情不是这样的。你不能指望这个查询会 return 你一个对象:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
如果您只想像问题中提到的那样使用查询生成器,则需要手动获取一个对象:
$data = DB::table('users')->where('id', 1)->first();
有了 Eloquent 你可以使用 updateOrCreate()
:
$data = User::where('id', 1)->updateOrCreate(['votes' => 123]);
这将 return 一个对象。 update()
将 return 布尔值,所以你不能在这里使用它。
在控制器中,您编写以下代码进行更新:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123])->get();
对于版本 6:另一种方式 eloquent 到 return 新的更新模型,通过 tap 链接更新方法调用:
$user = tap($user)->update(['votes' => 123]);
试试这个
$updated = tap(DB::table('users')->where('id', 1))
->update(['votes' => 123])
->first();
you get the first row again after update see example bellow
$user = User::where('id', 1);
$userOld = $user->first(); // will return the first row
$isUserUpdated = $user->update(['name'=>'new name']); // will return true or false
$updatedUser = $user->first(); // now it will return you the latest updated data
by this example you have old data and new data and is data updated result, now we can return new data.
return response()->json(['status' => $isUserUpdated,'data'=>$updatedUser], 200);
这也是 returns 更新的行:
$user = $user->fill(['votes' => 123])->save();
使用 Raw,如何return 收集更新的行?
例如:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
我期待 dd($updated)
到 return 更新集合行,但它 returned 1.
{{$updated->votes}} should return 123
事情不是这样的。你不能指望这个查询会 return 你一个对象:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
如果您只想像问题中提到的那样使用查询生成器,则需要手动获取一个对象:
$data = DB::table('users')->where('id', 1)->first();
有了 Eloquent 你可以使用 updateOrCreate()
:
$data = User::where('id', 1)->updateOrCreate(['votes' => 123]);
这将 return 一个对象。 update()
将 return 布尔值,所以你不能在这里使用它。
在控制器中,您编写以下代码进行更新:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123])->get();
对于版本 6:另一种方式 eloquent 到 return 新的更新模型,通过 tap 链接更新方法调用:
$user = tap($user)->update(['votes' => 123]);
试试这个
$updated = tap(DB::table('users')->where('id', 1))
->update(['votes' => 123])
->first();
you get the first row again after update see example bellow
$user = User::where('id', 1);
$userOld = $user->first(); // will return the first row
$isUserUpdated = $user->update(['name'=>'new name']); // will return true or false
$updatedUser = $user->first(); // now it will return you the latest updated data
by this example you have old data and new data and is data updated result, now we can return new data.
return response()->json(['status' => $isUserUpdated,'data'=>$updatedUser], 200);
这也是 returns 更新的行:
$user = $user->fill(['votes' => 123])->save();