hasMany(ItemGroupItem::class, 'group_id'); } /** * 获取物品组中的所有宝箱内容配置 * * @return HasMany */ public function chestContents(): HasMany { return $this->hasMany(ItemChestContent::class, 'group_id'); } /** * 根据权重随机获取物品组中的一个物品 * * @return ItemItem|null */ public function getRandomItem(): ?ItemItem { $groupItems = $this->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; } }