title($this->fruitName . '持有排名'); $this->dropdown([ '7' => '最近 7 天', '30' => '最近 30 天', '90' => '最近 90 天', 'all' => '全部时间', ]); } /** * 处理请求 * * @param Request $request * @return mixed|void */ public function handle(Request $request) { $timeRange = $request->get('option', 'all'); $data = $this->getFruitRankingData($timeRange); // 卡片内容 $this->withContent($data); } /** * 获取果实排名数据 * * @param string $timeRange * @return array */ protected function getFruitRankingData($timeRange) { // 构建查询 $query = ItemUser::with('user') ->select([ 'user_id', DB::raw('SUM(quantity) as total_quantity') ]) ->where('item_id', $this->fruitId) ->where('is_frozen', 0) // 排除冻结的物品 ->whereNull('expire_at'); // 排除已过期的物品 // 根据时间范围过滤 if ($timeRange !== 'all') { $days = (int)$timeRange; $query->where('created_at', '>=', now()->subDays($days)); } $rankings = $query->groupBy('user_id') ->orderByDesc('total_quantity') ->limit(20) ->get(); $result = []; foreach ($rankings as $index => $ranking) { $username = $ranking->user ? $ranking->user->username : null; $result[] = [ 'rank' => $index + 1, 'title' => $username ?: "用户{$ranking->user_id}", 'number' => number_format($ranking->total_quantity) . ' 个', ]; } // 如果没有数据,返回空排名提示 if (empty($result)) { $result[] = [ 'rank' => '-', 'title' => '暂无' . $this->fruitName . '持有数据', 'number' => '0 个', ]; } return $result; } }