Laravel 在使用Eloquent update时,同时将deleted_at不为null的值也一起update

如题,在批量更新时,update自动将软删除的数据过滤掉了,如何优雅地把deleted_at不为空的一起更新?

阅读 4.4k
2 个回答
User::where()->withTrashed()->update(...);
User::onlyTrashed()->update();

不仅要看源代码,也要看手册手册中明确说明过这个函数

根本不用withoutGlobalScope这么复杂的局部方法

翻了下源码,使用Eloquent时,加上 withoutGlobalScope方法并附上SoftDeletingScope的类为参数即可,eg:

$this->where('column', $value)->withoutGlobalScope(SoftDeletingScope::class)->update([
            'column' => 'new data'
        ]);

具体按步骤参看:

  1. IlluminateDatabaseQueryBuilder => update
  2. IlluminateDatabaseQueryBuilder => toBase
  3. IlluminateDatabaseQueryBuilder => applyScopes
  4. IlluminateDatabaseQueryBuilder => withoutGlobalScope

重点在 $this->scopes 这个变量中,只需要在update时,将这个软删除的扩展排除掉即可。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进