manghe/app/common/model/UserNewsFavorite.php
2025-06-22 19:12:07 +08:00

141 lines
3.6 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
declare(strict_types=1);
namespace app\common\model;
use think\Model;
/**
* 用户收藏资讯模型
* Class UserNewsFavorite
* @package app\common\model
*/
class UserNewsFavorite extends Model
{
// 设置表名
protected $name = 'user_news_favorite';
// 设置主键
protected $pk = 'id';
// 自动写入时间戳字段
protected $autoWriteTimestamp = true;
// 定义时间戳字段名
protected $createTime = 'create_time';
protected $updateTime = false; // 不使用更新时间
/**
* 查询用户是否收藏了指定新闻
* @param int $userId 用户ID
* @param int $newsId 新闻ID
* @return bool|array false表示未收藏array表示收藏信息
*/
public static function isFavorite($userId, $newsId)
{
$where = [
'user_id' => $userId,
'news_id' => $newsId,
'is_canceled' => 0, // 未取消收藏
];
$favorite = self::where($where)->find();
return $favorite ? $favorite->toArray() : false;
}
/**
* 添加收藏
* @param int $userId 用户ID
* @param int $newsId 新闻ID
* @return bool|array 收藏结果
*/
public static function addFavorite($userId, $newsId)
{
// 检查是否已收藏
$favorite = self::where([
'user_id' => $userId,
'news_id' => $newsId,
])->find();
if ($favorite) {
// 已收藏但被取消,则恢复收藏
if ($favorite['is_canceled'] == 1) {
$favorite->is_canceled = 0;
$favorite->cancel_time = null;
$favorite->create_time = date('Y-m-d H:i:s');
$favorite->save();
return $favorite->toArray();
}
// 已收藏未取消,返回已存在
return $favorite->toArray();
}
// 新增收藏
$model = new self();
$model->user_id = $userId;
$model->news_id = $newsId;
$model->is_canceled = 0;
$model->save();
return $model->toArray();
}
/**
* 取消收藏
* @param int $userId 用户ID
* @param int $newsId 新闻ID
* @return bool 取消结果
*/
public static function cancelFavorite($userId, $newsId)
{
$favorite = self::where([
'user_id' => $userId,
'news_id' => $newsId,
'is_canceled' => 0,
])->find();
if (!$favorite) {
return false;
}
$favorite->is_canceled = 1;
$favorite->cancel_time = date('Y-m-d H:i:s');
return $favorite->save() !== false;
}
/**
* 获取用户收藏列表
* @param int $userId 用户ID
* @param int $page 页码
* @param int $limit 每页条数
* @return array 收藏列表
*/
public static function getUserFavoriteList($userId, $page = 1, $limit = 10)
{
$where = [
'user_id' => $userId,
'is_canceled' => 0,
];
$list = self::where($where)
->with(['news' => function ($query) {
$query->field('id,title,cover_image,publish_time,author_name');
}])
->page($page, $limit)
->order('create_time', 'desc')
->select()
->toArray();
return $list;
}
/**
* 关联新闻表
* @return \think\model\relation\HasOne
*/
public function news()
{
return $this->hasOne(News::class, 'id', 'news_id');
}
}