【问题标题】:Return Collection after update()?update() 后返回集合?
【发布时间】:2017-03-29 12:47:25
【问题描述】:

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

例如:

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

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

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

【问题讨论】:

  • 更新是没有。此查询更新的行数
  • 你必须在更新语句后选择行

标签: php laravel laravel-5 laravel-5.3


【解决方案1】:

试试这个

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

【讨论】:

  • 最佳答案!
  • 就是这样! THX
  • 最简单最好的答案,你能说一下,Tap() 函数在这里做什么吗?
  • laravel 在 orm 中不工作 :(
  • Laravel 8.* 工作。
【解决方案2】:

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

$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]);

这将返回一个对象。 update() 将返回布尔值,所以你不能在这里使用它。

【讨论】:

  • 嗯。 updateOrCreate() 似乎不像他们的 docsimplementation 那样工作。这在超旧版本中有效吗?
【解决方案3】:

对于第 6 版:通过 tap 链接 update 方法调用来返回新的更新模型的另一种方式:

$user = tap($user)->update(['votes' => 123]);

【讨论】:

  • 在 laravel 7 中这样做,我得到了更新前的模型实例,而不是更新后
  • 它正在使用 laravel 6,我将更新答案以限制版本 6 的答案
【解决方案4】:

这也返回更新的行:

$user = $user->fill(['votes' => 123])->save();

【讨论】:

    【解决方案5】:

    更新后您再次获得第一行,请参见下面的示例

    $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
    

    通过这个例子,你有旧数据和新数据,是数据更新的结果,现在我们可以返回新数据了。

    return response()->json(['status' => $isUserUpdated,'data'=>$updatedUser], 200);
    

    【讨论】:

      【解决方案6】:

      在控制器中编写以下代码进行更新:

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

      【讨论】:

      • update() 返回一个整数,而不是查询构建器对象
      猜你喜欢
      • 1970-01-01
      • 2019-04-03
      • 2010-09-25
      • 2016-03-29
      • 2014-04-02
      • 2017-12-22
      • 2021-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多