I'l*_*ack 5 php laravel laravel-5 laravel-5.3
使用Raw,如何返回更新行的集合?
例如:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
Run Code Online (Sandbox Code Playgroud)
我期望dd($updated)返回集合的更新行,但返回1。
{{$updated->votes}} should return 123
Run Code Online (Sandbox Code Playgroud)
PW_*_*ons 18
尝试这个
$updated = tap(DB::table('users')->where('id', 1))
->update(['votes' => 123])
->first();
Run Code Online (Sandbox Code Playgroud)
Ale*_*nin 15
这不是它的工作原理。你不能指望这个查询会返回一个对象:
$updated = DB::table('users')->where('id', 1)->update(['votes' => 123]);
Run Code Online (Sandbox Code Playgroud)
如果您只想按照问题中提到的方式使用查询生成器,则需要手动获取一个对象:
$data = DB::table('users')->where('id', 1)->first();
Run Code Online (Sandbox Code Playgroud)
使用 Eloquent,您可以使用updateOrCreate():
$data = User::where('id', 1)->updateOrCreate(['votes' => 123]);
Run Code Online (Sandbox Code Playgroud)
这将返回一个对象。update()将返回布尔值,所以你不能在这里使用它。
另一种通过 tap 链接更新方法调用的 eloquent 返回新的更新模型的方法:
$user = tap($user)->update(['votes' => 123]);
Run Code Online (Sandbox Code Playgroud)