| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758 |
- <?php
- namespace App\Console\Commands;
- use App\Services\QuestionBulkImportService;
- use Illuminate\Console\Command;
- use Illuminate\Support\Facades\File;
- class QuestionsExportSqlCommand extends Command
- {
- protected $signature = 'questions:export-sql
- {--ids=* : 题目 id,可写多个 --ids=1 --ids=2 或 --ids=1,2,3}
- {--output= : SQL 输出路径;默认 storage/app/exports/questions_export_YYYYMMDDHHmmss.sql}
- {--with-id : 生成的 SQL 含 id 列(仅当必须在目标库对齐原主键时使用;默认不含 id,由目标库自增)}';
- protected $description = '将本地 questions 表中指定 id 导出为可复制到服务器的 MySQL 脚本';
- public function handle(QuestionBulkImportService $service): int
- {
- $idsOpt = $this->option('ids');
- $ids = [];
- if (is_array($idsOpt)) {
- foreach ($idsOpt as $chunk) {
- if (! is_string($chunk) && ! is_int($chunk)) {
- continue;
- }
- foreach (preg_split('/\s*,\s*/', (string) $chunk) ?: [] as $part) {
- if ($part === '') {
- continue;
- }
- $ids[] = (int) $part;
- }
- }
- }
- $ids = array_values(array_unique(array_filter($ids)));
- if ($ids === []) {
- $this->error('请至少指定一个 id,例如:php artisan questions:export-sql --ids=1,2,3');
- return self::FAILURE;
- }
- $includeId = (bool) $this->option('with-id');
- $sql = $service->exportIdsToMysqlScript($ids, $includeId);
- $outPath = $this->option('output');
- if (! is_string($outPath) || $outPath === '') {
- $outPath = storage_path('app/exports/questions_export_'.date('YmdHis').'.sql');
- }
- File::ensureDirectoryExists(dirname($outPath));
- File::put($outPath, $sql);
- $this->info('已导出 '.count($ids).' 个 id 的 SQL:'.$outPath);
- return self::SUCCESS;
- }
- }
|