update() 后返回集合?

2021-12-18 00:00:00 php laravel laravel-5 laravel-5.3

使用 Raw,如何返回更新行的集合?

Using Raw, how to return collection of updated row?

例如:

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

我期待 dd($updated) 返回更新后的集合行,但它返回了 1.

I was expecting dd($updated) to return updated row of collection but it returned 1.

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

推荐答案

它不是这样工作的.你不能指望这个查询会返回一个对象:

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

使用 Eloquent,您可以使用 updateOrCreate():

With Eloquent you can use the updateOrCreate():

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

这将返回一个对象.update() 将返回布尔值,因此您不能在这里使用它.

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

相关文章