manghe/app/common/model/UserPosterCache.php
2025-04-17 15:17:22 +08:00

82 lines
2.2 KiB
PHP

<?php
namespace app\common\model;
class UserPosterCache extends Base
{
// 设置当前模型对应的完整数据表名称
protected $table = 'user_poster_cache';
// 设置字段信息
protected $schema = [
'id' => 'int',
'user_id' => 'int',
'app_id' => 'string',
'template_hash' => 'string',
'cos_url' => 'string',
'file_size' => 'int',
'mime_type' => 'string',
'status' => 'int',
'created_at' => 'datetime',
'updated_at' => 'datetime',
'expires_at' => 'datetime',
];
/**
* 查找用户的有效海报缓存
*
* @param int $userId 用户ID
* @param string $templateHash 模板哈希
* @param string $appId 小程序APPID
* @return array|null 缓存记录
*/
public static function findValidCache($userId, $templateHash, $appId)
{
return self::where([
'user_id' => $userId,
'template_hash' => $templateHash,
'app_id' => $appId,
'status' => 1
])
->where('expires_at', '>', date('Y-m-d H:i:s'))
->find();
}
/**
* 失效指定用户的所有其他模板海报
*
* @param int $userId 用户ID
* @param string $currentTemplateHash 当前模板哈希
* @return bool 操作结果
*/
public static function invalidateOldCaches($userId, $currentTemplateHash)
{
return self::where('user_id', $userId)
->where('template_hash', '<>', $currentTemplateHash)
->update(['status' => 0]);
}
/**
* 清理过期的海报缓存记录
*
* @param int $limit 最大处理记录数
* @return int 清理的记录数
*/
public static function cleanExpiredCaches($limit = 100)
{
// 查询过期的缓存记录
$expiredCaches = self::where('expires_at', '<', date('Y-m-d H:i:s'))
->where('status', 1)
->limit($limit)
->select();
$cleanCount = 0;
foreach ($expiredCaches as $cache) {
$cache->status = 0;
$cache->save();
$cleanCount++;
}
return $cleanCount;
}
}