Files

99 lines
2.7 KiB
PHP
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
// +----------------------------------------------------------------------
// | YwxApp [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2026-2036 http://ywxapp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: ywxapp<admin@ywxapp.cn>
// +----------------------------------------------------------------------
declare (strict_types = 1);
namespace addon\blog\model;
use ywxapp\model\BaseModel;
use ywxapp\model\MemberUser;
class BlogFavorite extends BaseModel
{
// 设置数据表名
protected $name = 'blog_favorite';
// 设置主键
protected $pk = 'id';
// 自动写入时间戳(int 型 Unix 时间戳,匹配 create_at int 列)
protected $autoWriteTimestamp = 'int';
protected $createTime = 'create_at';
protected $updateTime = false;
// 定义允许写入的字段
protected $allowField = [
'uid', 'aid'
];
// 设置字段类型
protected $type = [
'id' => 'int',
'uid' => 'int',
'aid' => 'int',
'create_at' => 'int'
];
// 定义关联 - 用户(博客用户即主系统会员,统一使用 wxapp_user,主键 uid
public function user()
{
return $this->belongsTo(MemberUser::class, 'uid', 'uid');
}
// 定义关联 - 文章
public function article()
{
return $this->belongsTo(BlogArticle::class, 'aid');
}
// 检查用户是否已收藏
public static function hasFavorited($userId, $articleId)
{
return self::where('uid', $userId)
->where('aid', $articleId)
->count() > 0;
}
// 切换收藏状态
public static function toggle($userId, $articleId)
{
$favorite = self::where('uid', $userId)
->where('aid', $articleId)
->find();
if ($favorite) {
$favorite->delete();
return false; // 取消收藏
} else {
$favorite = new self();
$favorite->uid = $userId;
$favorite->aid = $articleId;
$favorite->save();
return true; // 添加收藏
}
}
// 获取用户收藏列表
public static function getUserFavorites($userId, $page = 1, $pageSize = 10)
{
return self::with(['article' =>
function($query) {
$query->with('author,category')->where('status', 1);
}])
->where('uid', $userId)
->order('create_at', 'desc')
->page($page, $pageSize)
->select();
}
}