mysql - 为什么 Laravel 5.8 不改表名迁移就不行?

标签 mysql sql laravel laravel-5.8

我有以下表架构;

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('account_type')->default('1,1,0');
            $table->string('theme')->default('light');
            $table->string('unique_id')->nullable();
            $table->string('avatar')->nullable();
            $table->rememberToken();
            $table->timestamps();
            $table->unsignedBigInteger('plan_id');
            $table->foreign('plan_id')->references('id')->on('plans');
            $table->unique('email');
        });

当我运行 migrate 时,它​​失败并出现错误:

errno: 150 "Foreign key constraint is incorrectly formed"

如果我删除外键,它仍然不起作用。

如果我将表名从“用户”更改为其他任何名称,它确实有效,但如果我再次运行它就会失败(需要再次更改表名)。

这是引用表的架构,此迁移也在用户迁移之前运行。

Schema::create('plans', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name')->unique();
            $table->float('cost', 8, 2)->nullable();
            $table->integer('free_trial');
            $table->string('renewal_rate');
            $table->string('features');
            $table->string('stripe_plan');
            $table->boolean('featured')->default(true);
            $table->string('permission');
            $table->timestamps();
        });

花了几天时间试图解决这个问题,每个人似乎都指出 bigIncrements/unsignedBigIncrements 与列名称中的错别字相同。我好像没有这个问题..

最佳答案

您想在计划 之前创建users 表。这就是您收到此错误的原因。首先,您需要创建不包含 'plan_id' 的用户表:

Schema::create('users', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('name');
            $table->string('email');
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->string('account_type')->default('1,1,0');
            $table->string('theme')->default('light');
            $table->string('unique_id')->nullable();
            $table->string('avatar')->nullable();
            $table->rememberToken();
            $table->timestamps();
            $table->unique('email');
        });

然后迁移两个表(usersplans)。迁移后,您需要创建新的迁移。

在控制台写入:php artisan make:migration add_plan_id_to_users --table=users

然后将其添加到您的新迁移中:

$table->unsignedBigInteger('plan_id');
$table->foreign('plan_id')->references('id')->on('plans');

关于mysql - 为什么 Laravel 5.8 不改表名迁移就不行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59448082/

相关文章:

php - 如何在一个类中访问 Laravel 单例?

php - 数据库数组只返回一行

php - MySQL 如何组合这些表?

mysql - 从重复行中选择最大值

sql - 为什么 count(1)、count(column) 和 count(*) 的成本相同?

mysql - 为什么我不断收到此错误 : ERROR 1064 (42000)?

php - ORM:友谊/好友关系

php - 模型上的 find() 在一个环境中将 id 给出为字符串,在其他环境中给出 int

mysql - 如何从mysql数据库中选择坐标

mysql - ORDER BY NULL 比 ORDER BY 列慢