FarmLand.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. namespace App\Module\Farm\Models;
  3. use App\Module\Farm\Enums\LAND_STATUS;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Database\Eloquent\Relations\BelongsTo;
  6. use Illuminate\Database\Eloquent\Relations\HasOne;
  7. /**
  8. * 土地信息模型
  9. * field start
  10. * @property int $id 主键ID
  11. * @property int $user_id 用户ID
  12. * @property int $position 土地位置(1-20)
  13. * @property int $land_type 土地类型:1普通,2红土,3黑土,4金,5蓝,6紫
  14. * @property int $status 土地状态:0空闲,1种植中,2灾害,3可收获,4枯萎
  15. * @property bool $has_crop 是否有作物:0无,1有
  16. * @property \Carbon\Carbon $created_at 创建时间
  17. * @property \Carbon\Carbon $updated_at 更新时间
  18. * field end
  19. * @property-read FarmUser $farmUser 关联的用户农场
  20. * @property-read FarmLandType $landType 关联的土地类型
  21. *
  22. * @package App\Module\Farm\Models
  23. */
  24. class FarmLand extends Model
  25. {
  26. /**
  27. * 与模型关联的表名
  28. *
  29. * @var string
  30. */
  31. protected $table = 'farm_land_users';
  32. /**
  33. * 可批量赋值的属性
  34. *
  35. * @var array
  36. */
  37. protected $fillable = [
  38. 'user_id',
  39. 'position',
  40. 'land_type',
  41. 'status',
  42. 'has_crop',
  43. ];
  44. // 暂时移除枚举类型转换,避免在表单处理时出现类型问题
  45. protected $casts = [
  46. // 'status' => LAND_STATUS::class
  47. 'has_crop' => 'boolean',
  48. ];
  49. /**
  50. * 获取关联的用户农场
  51. *
  52. * @return BelongsTo
  53. */
  54. public function farmUser(): BelongsTo
  55. {
  56. return $this->belongsTo(FarmUser::class, 'user_id', 'user_id');
  57. }
  58. /**
  59. * 获取关联的土地类型
  60. *
  61. * @return BelongsTo
  62. */
  63. public function landType(): BelongsTo
  64. {
  65. return $this->belongsTo(FarmLandType::class, 'land_type', 'id');
  66. }
  67. /**
  68. * 获取关联的作物
  69. *
  70. * @return HasOne
  71. */
  72. public function crop(): HasOne
  73. {
  74. return $this->hasOne(FarmCrop::class, 'land_id', 'id');
  75. }
  76. /**
  77. * 更新has_crop字段值
  78. * 根据当前状态自动更新has_crop字段
  79. *
  80. * @return void
  81. */
  82. public function updateHasCrop(): void
  83. {
  84. $this->has_crop = in_array($this->status, [
  85. LAND_STATUS::PLANTING->value, // 1 种植中
  86. LAND_STATUS::DISASTER->value, // 2 灾害
  87. LAND_STATUS::HARVESTABLE->value, // 3 可收获
  88. LAND_STATUS::WITHERED->value, // 4 枯萎
  89. ]);
  90. }
  91. }