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

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

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

回答
編輯回答
伐木累

翻了下源碼,使用Eloquent時(shí),加上 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

重點(diǎn)在 $this->scopes 這個(gè)變量中,只需要在update時(shí),將這個(gè)軟刪除的擴(kuò)展排除掉即可。

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

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

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

2018年8月4日 05:54