GenerateItemsJsonCommand.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Module\GameItems\Commands;
  3. use Illuminate\Console\Command;
  4. use App\Module\GameItems\Models\Item;
  5. use Illuminate\Support\Facades\File;
  6. class GenerateItemsJsonCommand extends Command
  7. {
  8. /**
  9. * 命令名称和签名
  10. *
  11. * @var string
  12. */
  13. protected $signature = 'gameitems:generate-json';
  14. /**
  15. * 命令描述
  16. *
  17. * @var string
  18. */
  19. protected $description = 'Generate items.json from Item table';
  20. /**
  21. * 执行命令
  22. */
  23. public function handle()
  24. {
  25. // 查询Item表中的数据
  26. $items = Item::query()
  27. ->select([
  28. 'id',
  29. 'name',
  30. 'description',
  31. 'sell_price',
  32. 'display_attributes'
  33. ])
  34. ->get()
  35. ->map(function ($item) {
  36. return [
  37. 'id' => $item->id,
  38. 'name' => $item->name,
  39. 'description' => $item->description,
  40. 'sell_price' => $item->sell_price,
  41. 'display_attributes' => $item->display_attributes
  42. ];
  43. })
  44. ->toArray();
  45. // 确保public/json目录存在
  46. $directory = public_path('json');
  47. if (!File::exists($directory)) {
  48. File::makeDirectory($directory, 0755, true);
  49. }
  50. // 准备完整数据,包含生成时间
  51. $data = [
  52. 'generated_at' => now()->toDateTimeString(),
  53. 'items' => $items
  54. ];
  55. // 写入JSON文件
  56. $json = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  57. File::put($directory . '/items.json', $json);
  58. $this->info('Successfully generated items.json with timestamp');
  59. }
  60. }