groupItems()->with('item')->get(); if ($groupItems->isEmpty()) { return null; } // 计算总权重 $totalWeight = $groupItems->sum('weight'); if ($totalWeight <= 0) { return $groupItems->first()->item; } // 随机选择 $randomValue = mt_rand(1, (int)($totalWeight * 1000)) / 1000; $currentWeight = 0; foreach ($groupItems as $groupItem) { $currentWeight += $groupItem->weight; if ($randomValue <= $currentWeight) { return $groupItem->item; } } // 如果由于浮点数精度问题没有选中,则返回最后一个 return $groupItems->last()->item; } }