fn_b/app/Console/Commands/ClearDb.php
2026-02-12 12:36:53 +08:00

41 lines
1.1 KiB
PHP
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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("点赞表很干净,没有过期数据。");
}
}
}