41 lines
1.1 KiB
PHP
Executable File
41 lines
1.1 KiB
PHP
Executable File
<?php
|
||
|
||
namespace App\Console\Commands;
|
||
|
||
use Illuminate\Console\Command;
|
||
use Illuminate\Support\Facades\DB;
|
||
use App\Models\ArticleLikes;
|
||
|
||
class ClearDb extends Command
|
||
{
|
||
protected $signature = 'clear_db';
|
||
protected $description = '清理过期数据';
|
||
|
||
public function handle(): void
|
||
{
|
||
$this->info("开始清理过期数据...");
|
||
|
||
$this->articleLikes();
|
||
|
||
$this->info("数据清理完成 !");
|
||
}
|
||
|
||
private function articleLikes()
|
||
{
|
||
// 1. 确定 30 天前的时间点
|
||
$oThresholdDate = now()->subDays(30);
|
||
|
||
// 2. 执行删除:直接在数据库层面一锅端
|
||
// 药水哥提示:这样写只发一条 DELETE SQL,效率最高!
|
||
$iDeletedCount = ArticleLikes::where('created_at', '<', $oThresholdDate)->delete();
|
||
|
||
// 3. 给点反馈,这叫“开发者的温柔”
|
||
if ($iDeletedCount > 0) {
|
||
$this->warn("已成功清理 {$iDeletedCount} 条 30 天前的点赞记录!");
|
||
} else {
|
||
$this->info("点赞表很干净,没有过期数据。");
|
||
}
|
||
}
|
||
|
||
}
|