fn_b/app/Services/CacheService.php
2026-08-04 18:26:48 +08:00

93 lines
3.3 KiB
PHP
Executable File
Raw Permalink 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\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_old(): 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;
// } // 真正问题在这里。这里生成缓存视图是基于ArticleLikes与刚才的代码脱节
public static function updateOrderLikes(): array
{
// 1. 基于 Articles 表按最后点赞时间倒序,涵盖真实赞与算法注入赞
$cArticles = Articles::where('iStatus', 1)
->whereNotNull('sLastLikedAt')
->orderBy('sLastLikedAt', 'desc')
->limit(5)
->get();
// 2. 构造与原结构完全一致的返回数组
$aHotArticles = $cArticles->map(function ($oArticle) {
return [
'iArticleId' => $oArticle->id,
'sLatestLikeTime' => $oArticle->sLastLikedAt,
'oArticle' => $oArticle,
];
})->toArray();
//tt($aHotArticles);
// 3. 存入缓存
Cache::forever(self::CACHE_KEYS['article_order_likes'], $aHotArticles);
return $aHotArticles;
}
}