调用了错误的迁移

Wrong migration called

我有 2 个迁移,第一个具有以下名称 2019_11_06_171637_create_settings_table.php 和结构:

class CreateSettingsTable extends Migration
{
  public function up()
  {
    Schema::create('settings', function (Blueprint $table) {
      //code
    });
  }
  //function down
}

第二个具有以下名称2020_07_08_246856_create_settings_table.php和结构:

class CreateAnotherSettingsTable extends Migration
{
  public function up()
  {
    Schema::create('another_settings', function (Blueprint $table) {
      //code
    });
  }
  //function down
}

当我 运行 php artisan migrate 所有迁移都进行顺利直到 Migrating: 2020_07_08_246856_create_settings_table - 它正在尝试 运行 previos 迁移(2019_11_06_171637_create_settings_table.php)并触发异常Table 'settings' already exists.

这是否意味着迁移文件的名称在日期和数字之后必须是唯一的?

我在某处读到 Laravel 使用迁移的文件名来为迁移调用正确的 class。我试图查找有关此的一些文档或参考资料,但我再也找不到了。您目前有两次相同的文件名(如果您忽略时间戳部分),这会导致 Laravel 调用相同的 class 两次。

如果您将第二个文件(带有 CreateAnotherSettingsTable class 的文件)重命名为 2020_07_08_246856_create_another_settings_table.php,您的问题将得到解决。

我觉得这很有趣,所以我查看了源代码。

\Illuminate\Database\Console\Migrations\TableGuesser 将使用迁移名称来确定 table 是否已经存在。

        // Next, we will attempt to guess the table name if this the migration has
        // "create" in the name. This will allow us to provide a convenient way
        // of creating migrations that create new tables for the application.
        if (! $table) {
            [$table, $create] = TableGuesser::guess($name);
        }

这是根据 artisan:makemigrate:install 命令执行的。

因此最终,由于您的迁移文件名为 create_settings_table.php,因此“设置”一词将用于检查。

laravel 用于此确定的代码是:

    const CREATE_PATTERNS = [
        '/^create_(\w+)_table$/',
        '/^create_(\w+)$/',
    ];

    const CHANGE_PATTERNS = [
        '/_(to|from|in)_(\w+)_table$/',
        '/_(to|from|in)_(\w+)$/',
    ];

    /**
     * Attempt to guess the table name and "creation" status of the given migration.
     *
     * @param  string  $migration
     * @return array
     */
    public static function guess($migration)
    {
        foreach (self::CREATE_PATTERNS as $pattern) {
            if (preg_match($pattern, $migration, $matches)) {
                return [$matches[1], $create = true];
            }
        }

        foreach (self::CHANGE_PATTERNS as $pattern) {
            if (preg_match($pattern, $migration, $matches)) {
                return [$matches[2], $create = false];
            }
        }
    }

所以您的解决方案是重命名其中一个迁移文件。

CreateAnotherSettingsTable会是最好的,标准如下,name