laravel update() 后返回集合?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43093965/
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
Return Collection after update()?
提问by I'll-Be-Back
Using Raw, how to return collection of updated row?
使用 Raw,如何返回更新行的集合?
For example:
例如:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
I was expecting dd($updated)
to return updated row of collection but it returned 1.
我期待dd($updated)
返回更新的集合行,但它返回了 1。
{{$updated->votes}} should return 123
回答by Alexey Mezenin
That's not how it works. You can't expect this query will return you an object:
这不是它的工作原理。你不能指望这个查询会返回一个对象:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
If you want to use Query Builder only as you mentioned in your question, you'll need to get an object manually:
如果您只想按照问题中提到的方式使用查询生成器,则需要手动获取一个对象:
$data = DB::table('users')->where('id', 1)->first();
With Eloquent you can use the updateOrCreate()
:
使用 Eloquent,您可以使用updateOrCreate()
:
$data = User::where('id', 1)->updateOrCreate(['votes' => 123]);
This will return an object. update()
will return boolean, so you can't use it here.
这将返回一个对象。update()
将返回布尔值,所以你不能在这里使用它。
回答by M.abdelrhman
another way with eloquent to return the new updated model by chaining the update method call through tap :
eloquent 的另一种方式是通过 tap 链接更新方法调用来返回新的更新模型:
$user = tap($user)->update(['votes' => 123]);
回答by PW_Parsons
Try this
尝试这个
$updated = tap(DB::table('users')->where('id', 1))
->update(['votes' => 123])
->first();
回答by DragonFire
You can do the following
您可以执行以下操作
use Response;
public function edit(Request $request, $id)
{
SomeModel::where('id', $id)->update([
'image' => $request->image,
'name' => $request->name,
]);
return Response::json(array(
'row' => SomeModel::findOrFail($id)));
}
回答by ram pratap singh
In controller you write below code for update :
在控制器中,您编写以下代码进行更新:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123])->get();