ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 라라벨 소프트 삭제(soft deleting)된 레코드를 주기적으로 삭제하기
    백엔드/laravel 2024. 1. 20. 14:26

     

    Prunable 트레이트를 모델에 추가하여 사용할 수 있습니다.

     

    use Illuminate\Database\Eloquent\Model;
    use Illuminate\Database\Eloquent\SoftDeletes;
    use Illuminate\Database\Eloquent\Prunable;

    class Post extends Model
    {
        use SoftDeletes, Prunable; // SoftDeletes와 Prunable 트레이트 추가

        // Prunable 트레이트를 사용하기 위한 메서드 추가
        public function prunable($query)
        {
            // 1개월 이전에 소프트 삭제된 레코드를 삭제하는 로직
            return $query->where('deleted_at', '<=', now()->subMonth());
        }
    }

     

    Prunable 트레이트를 추가하고, prunable 메서드를 정의하여 어떤 레코드를 삭제할지에 대한 로직을 지정합니다.

    위의 예제에서는 1개월 이전에 소프트 삭제된 레코드를 삭제하는 로직을 정의하였습니다.

     

     

    app/Console/Kernel.php 파일에 prunable 메서드를 사용하여,

    모델에서 이전 데이터를 정기적으로 정리할 수 있도록 스케줄러를 설정해보겠습니다.


    protected function schedule(Schedule $schedule)
    {
        // 모델의 prunable 메서드를 호출하여 데이터 정리
        $schedule->command('model:prune', ['--model' => 'App\Models\Post'])
                 ->daily();
    }

     

    위의 코드에서는 model:prune 명령어를 daily로 스케줄링하였습니다.

    이렇게 설정하면 매일 정해진 시간에 모델의 prunable 메서드에 정의한 조건에 맞는 데이터가 정리됩니다.

     

     

    이제 Laravel 스케줄러를 실행하여 설정한 주기에 따라 데이터를 정리할 수 있습니다.

     

    php artisan schedule:run

     

    이렇게 함으로써 Laravel에서는 정기적으로 데이터를 정리하여 데이터베이스를 깔끔하게 유지할 수 있습니다.

    댓글

Designed by Tistory.