Files
fn_b/app/Console/Commands/ClearDb.php
T
2026-08-18 17:58:27 +08:00

60 lines
1.7 KiB
PHP
Executable File

<?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()
{
$aCateId = Categories::whereIn("sSlug", ["freenode", "shadowrocketids"])->pluck("id")->toArray();
if (empty($aCateId)) {
$this->info("没有匹配的分类,跳过清理");
return;
}
$sDate = date('Y-m-d', strtotime('-180 days'));
$i = Articles::whereIn("iCategoryId", $aCateId)->whereDate("created_at", "<", $sDate)->delete();
$this->info("清理 {$i} 条数据");
}
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("点赞表很干净,没有过期数据。");
}
}
}