noouh/laravel-multiple-migrations

一个用于从多个路径运行迁移的 Laravel 扩展包。

v0.1 2024-08-01 08:13 UTC

This package is auto-updated.

Last update: 2024-10-01 08:35:26 UTC


README

一个用于从多个路径运行迁移的 Laravel 扩展包。

安装

composer require noouh/laravel-multiple-migrations

使用

php artisan migrate:multiple database/migrations

许可证

MIT

为确保命令跳过任何失败的迁移或如果表已存在的情况,您可以在迁移调用中包含 try-catch 块。以下是修改命令类以处理此情况的方法

更新后的命令类

<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Exception;

class MigrateMultiplePaths extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'migrate:multiple {paths*}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run migrations from multiple paths';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $paths = $this->argument('paths');

        foreach ($paths as $path) {
            $this->info("Running migrations in: $path");

            $migrationFiles = $this->getMigrationFiles($path);

            foreach ($migrationFiles as $file) {
                $this->info("Running migration: $file");
                try {
                    $this->call('migrate', [
                        '--path' => $file,
                    ]);
                } catch (Exception $e) {
                    $this->error("Failed to run migration: $file. Error: " . $e->getMessage());
                }
            }
        }

        return 0;
    }

    /**
     * Get all migration files from the specified directory.
     *
     * @param string $path
     * @return array
     */
    protected function getMigrationFiles($path)
    {
        $files = [];

        if (File::isDirectory($path)) {
            $files = File::allFiles($path);
        }

        return array_map(function ($file) use ($path) {
            return $path . '/' . $file->getFilename();
        }, $files);
    }
}

说明

  • Try-Catch 块:每个迁移都包裹在一个 try-catch 块中,以处理迁移过程中可能发生的任何异常。如果捕获到异常,将记录错误消息,并命令继续到下一个迁移文件。
  • 错误处理:如果表已存在或发生其他错误,它将被捕获并跳过,而不会停止剩余迁移的执行。

注册命令

确保命令已在 app/Console/Kernel.php 文件中注册

protected $commands = [
    \App\Console\Commands\MigrateMultiplePaths::class,
];

运行命令

您可以通过运行自定义命令并传递提取迁移的路径来执行该命令

php artisan migrate:multiple /mnt/data/extracted

此命令将在指定的目录中检测所有迁移文件,尝试运行它们,并跳过任何失败或表已存在的迁移。