| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103 |
- <?php
- namespace App\Module\GameItems\Models;
- use Illuminate\Database\Eloquent\Relations\HasMany;
- use UCore\ModelCore;
- /**
- * 物品组
- *
- * field start
- * @property int $id 物品组ID,主键
- * @property string $name 物品组名称
- * @property string $code 物品组编码(唯一)
- * @property string $description 物品组描述
- * @property \Carbon\Carbon $created_at 创建时间
- * @property \Carbon\Carbon $updated_at 更新时间
- * field end
- */
- class ItemGroup extends ModelCore
- {
- /**
- * 与模型关联的表名
- *
- * @var string
- */
- protected $table = 'item_groups';
- // attrlist start
- protected $fillable = [
- 'id',
- 'name',
- 'code',
- 'description',
- ];
- // attrlist end
- /**
- * 可批量赋值的属性
- *
- * @var array
- */
- protected $fillable = [
- 'name',
- 'code',
- 'description',
- ];
- /**
- * 获取物品组中的所有物品
- *
- * @return HasMany
- */
- public function groupItems(): HasMany
- {
- return $this->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;
- }
- }
|