错误的迁移称为

问题描述

我有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使用迁移文件名来为迁移调用正确的类。我试图查找有关此问题的一些文档或参考,但是现在找不到了。当前,您具有两次相同的文件名(如果忽略了时间戳部分),这导致Laravel两次调用相同的类。

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

,

我发现这非常有趣,因此我在源代码中进行了浏览。

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

        // 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,$matches)) {
                return [$matches[2],$create = false];
            }
        }
    }

因此,您的解决方案是重命名这些迁移文件之一。

CreateAnotherSettingsTable将是最好的,标准的跟随者,名字