Files
fn_b/app/Console/Commands/ClearDb.php
T

49 lines
1.3 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Models\ArticleLikes;
use App\Models\Categories;
use App\Models\Articles;
class ClearDb extends Command
{
protected $signature = 'clear_db';
protected $description = '清理过期数据';
public function handle(): void
{
$this->info("开始清理过期数据...");
$this->article();
$this->articleLikes();
$this->info("数据清理完成 !");
}
private function article()
{
$this->info('正文按内容保留策略维护,不再按180天自动删除。');
}
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("点赞表很干净,没有过期数据。");
}
}
}