鍍金池/ 問答/PHP/ Laravel 在使用Eloquent update時,同時將deleted_a

Laravel 在使用Eloquent update時,同時將deleted_at不為null的值也一起update

如題,在批量更新時,update自動將軟刪除的數(shù)據(jù)過濾掉了,如何優(yōu)雅地把deleted_at不為空的一起更新?

回答
編輯回答
伐木累

翻了下源碼,使用Eloquent時,加上 withoutGlobalScope方法并附上SoftDeletingScope的類為參數(shù)即可,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時,將這個軟刪除的擴展排除掉即可。

2018年3月1日 15:28
編輯回答
野橘
User::where()->withTrashed()->update(...);
User::onlyTrashed()->update();

不僅要看源代碼,也要看手冊手冊中明確說明過這個函數(shù)

根本不用withoutGlobalScope這么復(fù)雜的局部方法

2018年8月4日 05:54