QuestionsExportSqlCommand.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Console\Commands;
  3. use App\Services\QuestionBulkImportService;
  4. use Illuminate\Console\Command;
  5. use Illuminate\Support\Facades\File;
  6. class QuestionsExportSqlCommand extends Command
  7. {
  8. protected $signature = 'questions:export-sql
  9. {--ids=* : 题目 id,可写多个 --ids=1 --ids=2 或 --ids=1,2,3}
  10. {--output= : SQL 输出路径;默认 storage/app/exports/questions_export_YYYYMMDDHHmmss.sql}
  11. {--with-id : 生成的 SQL 含 id 列(仅当必须在目标库对齐原主键时使用;默认不含 id,由目标库自增)}';
  12. protected $description = '将本地 questions 表中指定 id 导出为可复制到服务器的 MySQL 脚本';
  13. public function handle(QuestionBulkImportService $service): int
  14. {
  15. $idsOpt = $this->option('ids');
  16. $ids = [];
  17. if (is_array($idsOpt)) {
  18. foreach ($idsOpt as $chunk) {
  19. if (! is_string($chunk) && ! is_int($chunk)) {
  20. continue;
  21. }
  22. foreach (preg_split('/\s*,\s*/', (string) $chunk) ?: [] as $part) {
  23. if ($part === '') {
  24. continue;
  25. }
  26. $ids[] = (int) $part;
  27. }
  28. }
  29. }
  30. $ids = array_values(array_unique(array_filter($ids)));
  31. if ($ids === []) {
  32. $this->error('请至少指定一个 id,例如:php artisan questions:export-sql --ids=1,2,3');
  33. return self::FAILURE;
  34. }
  35. $includeId = (bool) $this->option('with-id');
  36. $sql = $service->exportIdsToMysqlScript($ids, $includeId);
  37. $outPath = $this->option('output');
  38. if (! is_string($outPath) || $outPath === '') {
  39. $outPath = storage_path('app/exports/questions_export_'.date('YmdHis').'.sql');
  40. }
  41. File::ensureDirectoryExists(dirname($outPath));
  42. File::put($outPath, $sql);
  43. $this->info('已导出 '.count($ids).' 个 id 的 SQL:'.$outPath);
  44. return self::SUCCESS;
  45. }
  46. }