Blame view
app/Console/Commands/RemoveOldUsers.php
3.3 KB
09a2fc9d8 messages and subs... |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
<?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; class RemoveOldUsers extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'users:remove-old'; /** * The console command description. * * @var string */ protected $description = 'Remove old users and related data'; /** * Execute the console command. */ public function handle() { $date = '2024-11-30 00:00:00'; $users = DB::table('users') ->where('created_at', '<', $date) ->pluck('id'); if ($users->isEmpty()) { $this->info('No users to delete.'); return 0; } $this->info('Found ' . $users->count() . ' users to delete.'); $userRelatedTables = [ 'answers', 'chats', 'employers', 'group_users', 'group_works', // 'like_vacancy', // 'like_worker', 'media', 'messages', 'messages_requests', 'static_workers', 'workers', ]; $workerEmployerRelatedTables = [ 'ad_employers' => 'employer_id', 'answers' => 'employer_id', 'employers_mains' => 'employer_id', 'employer_autolift_options' => 'employer_id', 'flots' => 'employer_id', 'place_works' => 'worker_id', 'prev_company' => 'worker_id', 'response_works' => 'worker_id', 'sertifications' => 'worker_id', 'title_workers' => 'worker_id', 'worker_autolift_options' => 'worker_id', ]; try { DB::beginTransaction(); foreach ($userRelatedTables as $table) { DB::table($table)->whereIn('user_id', $users)->delete(); $this->info("Removed related records from table: $table"); } $workerIds = DB::table('workers')->whereIn('user_id', $users)->pluck('id'); $employerIds = DB::table('employers')->whereIn('user_id', $users)->pluck('id'); foreach ($workerEmployerRelatedTables as $table => $column) { DB::table($table)->whereIn($column, str_contains($column, 'worker') ? $workerIds : $employerIds)->delete(); $this->info("Removed related records for table: $table"); } foreach (['like_vacancy', 'like_worker'] as $table) { DB::table($table)->whereIn('user_id', $users->map(fn($id) => (string)$id))->delete(); DB::table($table)->whereIn('user_id', $users->map(fn($id) => (string)$id))->delete(); $this->info("Removed related records from table: $table (VARCHAR user_id)"); } DB::table('workers')->whereIn('id', $workerIds)->delete(); DB::table('employers')->whereIn('id', $employerIds)->delete(); DB::table('users')->whereIn('id', $users)->delete(); DB::commit(); $this->info('All related data and users have been removed successfully.'); } catch (\Exception $e) { DB::rollBack(); $this->error('An error occurred: ' . $e->getMessage()); } return 0; } } |