UpdateCropGrowthCommand.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace App\Module\Farm\Commands;
  3. use App\Module\Farm\Enums\GROWTH_STAGE;
  4. use App\Module\Farm\Logics\CropLogic;
  5. use App\Module\Farm\Models\FarmCrop;
  6. use Illuminate\Console\Command;
  7. use Illuminate\Support\Facades\Log;
  8. /**
  9. * 更新作物生长状态命令
  10. */
  11. class UpdateCropGrowthCommand extends Command
  12. {
  13. /**
  14. * 命令名称
  15. *
  16. * @var string
  17. */
  18. protected $signature = 'farm:update-crop-growth';
  19. /**
  20. * 命令描述
  21. *
  22. * @var string
  23. */
  24. protected $description = '更新作物生长状态';
  25. /**
  26. * 执行命令
  27. *
  28. * @return int
  29. */
  30. public function handle()
  31. {
  32. $this->info('开始更新作物生长状态...');
  33. try {
  34. // 获取需要更新生长阶段的作物
  35. /**
  36. * @var \Illuminate\Database\Eloquent\Collection $crops
  37. */
  38. $crops = FarmCrop::whereNotNull('stage_end_time')
  39. ->where('stage_end_time', '<=', now())
  40. ->where('growth_stage', '<', GROWTH_STAGE::WITHERED->value)
  41. ->get();
  42. $this->info("找到 {$crops->count()} 个需要更新的作物");
  43. $updatedCount = 0;
  44. foreach ($crops as $crop) {
  45. $userId = $crop->user_id;
  46. $oldStage = $crop->growth_stage;
  47. // 使用CropLogic的updateGrowthStage方法,确保所有逻辑都正确执行
  48. $cropLogic = new CropLogic();
  49. $updated = $cropLogic->updateGrowthStage($crop->id);
  50. if ($updated) {
  51. $updatedCount++;
  52. // 重新获取作物信息以显示更新后的状态
  53. $crop->refresh();
  54. // 获取阶段名称用于显示
  55. $oldStageName = GROWTH_STAGE::getName($oldStage->value);
  56. $newStageName = GROWTH_STAGE::getName($crop->growth_stage->value);
  57. $this->info("作物 ID: {$crop->id}, 用户 ID: {$userId}, 阶段: {$oldStageName} -> {$newStageName}");
  58. }
  59. }
  60. $this->info("成功更新 {$updatedCount} 个作物的生长状态");
  61. Log::info('作物生长状态更新成功', [
  62. 'total' => $crops->count(),
  63. 'updated' => $updatedCount
  64. ]);
  65. return 0;
  66. } catch (\Exception $e) {
  67. $this->error('作物生长状态更新失败: ' . $e->getMessage());
  68. Log::error('作物生长状态更新失败', [
  69. 'error' => $e->getMessage(),
  70. 'trace' => $e->getTraceAsString()
  71. ]);
  72. return 1;
  73. }
  74. }
  75. }