'integer', 'to_user_id' => 'integer', 'from_user_id' => 'integer', 'type' => 'integer', 'related_id' => 'integer', 'is_read' => 'integer' ]; public function getCreatetimeTextAttr($value, $data) { $value = $value ? $value : ($data['createtime'] ?? ""); return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value; } // 关联用户信息 public function user() { return $this->belongsTo('User', 'user_id', 'id'); } public function fromUser() { return $this->belongsTo('User', 'from_user_id', 'id'); } /** * 创建好友申请通知 */ public static function createFriendRequestNotification($params) { $message=$params['content']; $toUserId = $params['to_user_id']; $fromUserId = $params['from_user_id']; $content = $message ? "用户 " . User::get($fromUserId)['nickname'] . " 申请添加您为好友:" . $message : "用户 " . User::get($fromUserId)['nickname'] . " 申请添加您为好友"; return self::create([ 'to_user_id' => $toUserId, 'type' => self::TYPE_FRIEND_REQUEST, 'content' => $content, ]); } /** * 创建申请结果通知 */ public static function createRequestResultNotification($params) { $result = $params['status']; $fromUserId = $params['from_user_id']; $toUserId = $params['to_user_id']; $resultText = $result == 1 ? '同意' : '拒绝'; $content = "用户 " . User::get($fromUserId)['nickname'] . " 已{$resultText}您的好友申请"; return self::create([ 'to_user_id' => $toUserId, 'type' => self::TYPE_REQUEST_RESULT, 'content' => $content, ]); } /** * 创建好友添加成功通知 */ public static function createFriendAddedNotification($userId, $friendId) { $content = "您与 " . User::get($friendId)['nickname'] . " 已成为好友"; return self::create([ 'user_id' => $userId, 'from_user_id' => $friendId, 'type' => self::TYPE_FRIEND_ADDED, 'content' => $content ]); } /** * 获取用户未读通知数量 */ public static function getUnreadCount($userId) { return self::where(['to_user_id' => $userId, 'is_read' => 0])->count(); } /** * 标记通知为已读 */ public static function markAsRead($notificationId, $userId = null) { $where = ['id' => $notificationId]; if ($userId) { $where['to_user_id'] = $userId; } return self::update(['is_read' => 1], $where); } /** * 批量标记通知为已读 */ public static function markBatchAsRead($user_id, $ids = []) { $where = ['to_user_id' => $user_id]; if (!empty($ids)) { $where['id'] = ['in', $ids]; } return self::where($where)->update(['is_read' => 1]); } /** * 获取用户通知列表 */ public static function getNotificationList($userId) { return self::where(['to_user_id' => $userId]) ->order('id DESC') ->paginate(); } /** * 删除过期通知(保留最近30天的记录) */ public static function cleanupExpiredNotifications() { $expireTime = time() - 30 * 24 * 3600; // 30天前的时间戳 return self::where('created_at', '<', $expireTime)->delete(); } }