fix(Post): 修正点击数缓存处理逻辑

- 使用 getOrigin 方法替代直接访问 data 数组,提高健壮性
- 修复缓存值为空字符串时的类型转换问题
- 在 setHitsAttr 中预加载 hits_title 属性确保缓存存在
- 统一使用整型返回值,避免类型不一致
This commit is contained in:
augushong
2026-05-02 21:24:04 +08:00
parent 9dce9854c8
commit 45efbc24f6

View File

@@ -269,24 +269,20 @@ class Post extends Base
public function getHitsTitleAttr()
{
// 新建对象时直接返回 0
if (!isset($this->data['id']) || empty($this->data['id'])) {
$id = $this->getOrigin('id');
if (empty($id)) {
return 0;
}
$id = $this->data['id'];
$cache_key = static::CACHE_KEY_HITS . $id;
$value = Cache::get($cache_key);
if (!is_null($value)) {
return $value;
if (!is_null($value) && $value !== '') {
return (int) $value;
}
// 安全获取hits 可能尚未存在于 data 中
$value = array_key_exists('hits', $this->data) ? $this->data['hits'] : 0;
$value = (int) ($this->getOrigin('hits') ?: 0);
Cache::set($cache_key, $value, 600);
return $value;
@@ -294,15 +290,14 @@ class Post extends Base
public function setHitsAttr($value)
{
// 新建对象(无 id直接返回值跳过缓存操作
if (!isset($this->data['id']) || empty($this->data['id'])) {
$id = $this->getOrigin('id');
if (empty($id)) {
return $value;
}
$id = $this->data['id'];
$cache_key = static::CACHE_KEY_HITS . $id;
$this->getAttr('hits_title');
Cache::inc($cache_key);
return $value;