'array', 'status' => APP_MESSAGE_STATUS::class, 'type' => APP_MESSAGE_TYPE::class, 'sender_type' => APP_SENDER_TYPE::class ]; /** * 获取消息接收者列表 * * 一条消息可以有多个接收者,这里定义了一对多关系 * * @return HasMany */ public function recipients(): HasMany { return $this->hasMany(AppMessageRecipient::class, 'message_id'); } /** * 获取指定用户的未读消息数量 * * @param int $userId 用户ID * @return int 未读消息数量 */ public static function getUnreadCount(int $userId): int { return static::whereHas('recipients', function ($query) use ($userId) { $query->where('user_id', $userId) ->where('is_read', false); })->count(); } /** * 将消息标记为已读 * * @param int $messageId 消息ID * @param int $userId 用户ID * @return bool 是否标记成功 */ public static function markAsRead(int $messageId, int $userId): bool { return static::whereHas('recipients', function ($query) use ($messageId, $userId) { $query->where('message_id', $messageId) ->where('user_id', $userId); })->update([ 'is_read' => true, 'read_at' => now() ]); } }