1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Minepic\Console\Commands; |
6
|
|
|
|
7
|
|
|
use Minepic\Models\Account; |
8
|
|
|
use Illuminate\Console\Command; |
9
|
|
|
|
10
|
|
|
/** |
11
|
|
|
* Class CleanAccountsTable. |
12
|
|
|
*/ |
13
|
|
|
class CleanAccountsTable extends Command |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* The console command name. |
17
|
|
|
* |
18
|
|
|
* @var string |
19
|
|
|
*/ |
20
|
|
|
protected $name = 'minepic:clean-accounts'; |
21
|
|
|
|
22
|
|
|
/** |
23
|
|
|
* The console command description. |
24
|
|
|
* |
25
|
|
|
* @var string |
26
|
|
|
*/ |
27
|
|
|
protected $description = 'Clean the account table.'; |
28
|
|
|
|
29
|
|
|
/** |
30
|
|
|
* Execute the console command. |
31
|
|
|
*/ |
32
|
|
|
public function handle(): int |
33
|
|
|
{ |
34
|
|
|
$this->info('Selecting all duplicates...'); |
35
|
|
|
|
36
|
|
|
$subQuery = Account::query() |
37
|
|
|
->select('username', app('db')->raw('COUNT(id) AS total')) |
38
|
|
|
->groupBy('username') |
39
|
|
|
->orderBy('total', 'DESC') |
40
|
|
|
->toSql(); |
41
|
|
|
|
42
|
|
|
/** @var \Illuminate\Support\Collection $results */ |
43
|
|
|
$results = app('db')->table(app('db')->raw(" ({$subQuery}) AS subq")) |
44
|
|
|
->where('total', '>', 1) |
45
|
|
|
->get(); |
46
|
|
|
|
47
|
|
|
if ($results->count() > 0) { |
48
|
|
|
foreach ($results as $result) { |
49
|
|
|
$this->info("Removing {$result->username}..."); |
50
|
|
|
$deletedRows = Account::query() |
51
|
|
|
->where('username', $result->username) |
52
|
|
|
->orderBy('updated_at', 'ASC') |
53
|
|
|
->take(1) |
54
|
|
|
->delete(); |
55
|
|
|
if ($deletedRows === 1) { |
56
|
|
|
$this->info('Deleted'); |
57
|
|
|
} else { |
58
|
|
|
$this->error('Error!'); |
59
|
|
|
} |
60
|
|
|
$this->info('--------------------------------------------'); |
61
|
|
|
} |
62
|
|
|
} else { |
63
|
|
|
$this->info('No duplicates found'); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
return 0; |
67
|
|
|
} |
68
|
|
|
} |
69
|
|
|
|