Return Collection after update()?

╄→尐↘猪︶ㄣ 提交于 2019-12-21 05:23:07

问题


Using Raw, how to return collection of updated row?

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.

{{$updated->votes}} should return 123

回答1:


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():

$data = User::where('id', 1)->updateOrCreate(['votes' => 123]);

This will return an object. update() will return boolean, so you can't use it here.




回答2:


All functions regarding database returns same value as you would run a raw query through php.

If you run a UPDATE or INSERT query in PHP, it returns boolean. Same in Laravel update() returns 1 or 0.

Its totally normal, only functions which uses SELECT behind the scenes will return an object containing row. FOr example: first(), get(), find() etc.




回答3:


In controller you write below code for update :

 $updated = DB::table('users')->where('id', 1)->update(['votes' => 123])->get();


来源:https://stackoverflow.com/questions/43093965/return-collection-after-update

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!