69 lines
2.3 KiB
PHP
Executable File
69 lines
2.3 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
//use App\Models\Categories;
|
|
use App\Models\Articles;
|
|
use App\Models\ArticleLikes;
|
|
//use App\Models\Tags;
|
|
use Illuminate\Support\Facades\Cache;
|
|
|
|
class CacheService
|
|
{
|
|
public const CACHE_KEYS = [
|
|
'article_order_likes' => 'article_order_likes',
|
|
];
|
|
|
|
// public static function updateOrderLikes(): array
|
|
// {
|
|
// $oStartDate = now()->subDays(30);
|
|
//
|
|
// $aHotArticles = ArticleLikes::select('iArticleId', \DB::raw('count(*) as iTotalLikes'))
|
|
// ->where('created_at', '>=', $oStartDate)
|
|
// ->groupBy('iArticleId')
|
|
// ->orderBy('iTotalLikes', 'desc')
|
|
// ->with(['oArticle' => function($oQuery) {
|
|
// $oQuery->where('iStatus', 1);
|
|
// }])
|
|
// ->limit(10)
|
|
// ->get()
|
|
// ->filter(fn($oItem) => $oItem->oArticle !== null)
|
|
// ->toArray(); // 存入缓存建议转成数组,性能更稳
|
|
//
|
|
// // 存入缓存,永久保存(直到下一次更新)
|
|
// Cache::forever(self::CACHE_KEYS['article_order_likes'], $aHotArticles);
|
|
//
|
|
// return $aHotArticles;
|
|
// }
|
|
|
|
public static function updateOrderLikes(): array
|
|
{
|
|
// 1. 获取最近点赞的文章ID流
|
|
// 使用 max(id) 或 max(created_at) 来确保每个文章只出现一次,且取的是它最后一次被点赞的时间
|
|
$aHotArticles = ArticleLikes::select('iArticleId', \DB::raw('MAX(created_at) as sLatestLikeTime'))
|
|
->whereHas('oArticle', function($oQuery) {
|
|
$oQuery->where('iStatus', 1); // 只看发布状态的文章
|
|
})
|
|
->groupBy('iArticleId')
|
|
->orderBy('sLatestLikeTime', 'desc') // 按最后一次点赞时间倒序
|
|
->limit(10)
|
|
->with('oArticle') // 预加载文章详情
|
|
->get()
|
|
->map(function($oItem) {
|
|
// 格式化输出,把文章对象和点赞时间揉在一起
|
|
return [
|
|
'iArticleId' => $oItem->iArticleId,
|
|
'sLatestLikeTime' => $oItem->sLatestLikeTime,
|
|
'oArticle' => $oItem->oArticle
|
|
];
|
|
})
|
|
->toArray();
|
|
|
|
// 2. 存入缓存
|
|
Cache::forever(self::CACHE_KEYS['article_order_likes'], $aHotArticles);
|
|
|
|
return $aHotArticles;
|
|
}
|
|
|
|
}
|