ItemGroup.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. <?php
  2. namespace App\Module\GameItems\Models;
  3. use Illuminate\Database\Eloquent\Relations\HasMany;
  4. use UCore\ModelCore;
  5. /**
  6. * 物品组
  7. *
  8. * field start
  9. * @property int $id 物品组ID,主键
  10. * @property string $name 物品组名称
  11. * @property string $code 物品组编码(唯一)
  12. * @property string $description 物品组描述
  13. * @property \Carbon\Carbon $created_at 创建时间
  14. * @property \Carbon\Carbon $updated_at 更新时间
  15. * field end
  16. */
  17. class ItemGroup extends ModelCore
  18. {
  19. /**
  20. * 与模型关联的表名
  21. *
  22. * @var string
  23. */
  24. protected $table = 'item_groups';
  25. // attrlist start
  26. protected $fillable = [
  27. 'id',
  28. 'name',
  29. 'code',
  30. 'description',
  31. ];
  32. // attrlist end
  33. /**
  34. * 可批量赋值的属性
  35. *
  36. * @var array
  37. */
  38. protected $fillable = [
  39. 'name',
  40. 'code',
  41. 'description',
  42. ];
  43. /**
  44. * 获取物品组中的所有物品
  45. *
  46. * @return HasMany
  47. */
  48. public function groupItems(): HasMany
  49. {
  50. return $this->hasMany(ItemGroupItem::class, 'group_id');
  51. }
  52. /**
  53. * 获取物品组中的所有宝箱内容配置
  54. *
  55. * @return HasMany
  56. */
  57. public function chestContents(): HasMany
  58. {
  59. return $this->hasMany(ItemChestContent::class, 'group_id');
  60. }
  61. /**
  62. * 根据权重随机获取物品组中的一个物品
  63. *
  64. * @return ItemItem|null
  65. */
  66. public function getRandomItem(): ?ItemItem
  67. {
  68. $groupItems = $this->groupItems()->with('item')->get();
  69. if ($groupItems->isEmpty()) {
  70. return null;
  71. }
  72. // 计算总权重
  73. $totalWeight = $groupItems->sum('weight');
  74. if ($totalWeight <= 0) {
  75. return $groupItems->first()->item;
  76. }
  77. // 随机选择
  78. $randomValue = mt_rand(1, (int)($totalWeight * 1000)) / 1000;
  79. $currentWeight = 0;
  80. foreach ($groupItems as $groupItem) {
  81. $currentWeight += $groupItem->weight;
  82. if ($randomValue <= $currentWeight) {
  83. return $groupItem->item;
  84. }
  85. }
  86. // 如果由于浮点数精度问题没有选中,则返回最后一个
  87. return $groupItems->last()->item;
  88. }
  89. }