Laravel 的软删除功能通过保留数据库中的已删除记录来维护数据完整性。但是,有时您需要永久删除这些记录。新的 forceDestroy
方法简化了此过程,无需在永久删除之前先检索模型。
此方法在执行清理操作、管理用户数据以符合隐私合规性或实施需要从数据库中完全删除某些记录的审核系统时特别有用。
以下是如何使用 forceDestroy
方法的示例:
use App\Models\Post; // 永久删除单个记录 Post::forceDestroy($id); // 删除多条记录 Post::forceDestroy([$id1, $id2, $id3]);
让我们来看一个数据清理服务的实际示例:
<?php namespace App\Services; use App\Models\User; use App\Models\Content; use Illuminate\Support\Facades\Log; use App\Events\UserDataPurged; class DataCleanupService { public function purgeInactiveUserData(int $monthsInactive = 12) { $inactiveUsers = User::onlyTrashed() ->where('deleted_at', '<', now()->subMonths($monthsInactive)) ->pluck('id'); if ($inactiveUsers->isEmpty()) { return ['message' => '没有需要清理的非活动用户']; } // 首先清理相关内容 $contentCount = Content::onlyTrashed() ->whereIn('user_id', $inactiveUsers) ->count(); Content::whereIn('user_id', $inactiveUsers) ->forceDestroy(); // 永久删除用户帐户 $userCount = User::forceDestroy($inactiveUsers); Log::info('完成用户数据清理', [ '已删除用户数量' => $userCount, '已删除内容数量' => $contentCount ]); UserDataPurged::dispatch($inactiveUsers); return [ '已清理用户数量' => $userCount, '已清理内容数量' => $contentCount, 'message' => "已成功清理 {$userCount} 个非活动用户帐户" ]; } }
forceDestroy
方法简化了永久删除操作,使您的代码在管理软删除记录时更简洁高效。
以上是Laravel的永久记录删除的详细内容。更多信息请关注PHP中文网其他相关文章!