laravel迁移SQLSTATE [HY000]

时间:2020-06-23 06:45:57

标签: mysql laravel database-migration

由于此错误,我无法运行迁移命令:

SQLSTATE [HY000]:常规错误:1215无法添加外键 约束(SQL:alter table user_schools添加约束 user_schools_school_id_foreign个外键(school_id)引用 schoolsid)在删除级联上)

代码

users

 Schema::create('users', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->softDeletes('deleted_at', 0);
        $table->timestamps();
 });

schools

Schema::create('schools', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->string('code')->unique();
        $table->string('name');
        $table->set('type', ['TK', 'SD', 'SMP', 'SMA', 'SMK']);
        $table->softDeletes('deleted_at', 0);
        $table->timestamps();
});

user_schools

Schema::create('user_schools', function (Blueprint $table) {
        $table->uuid('id')->primary();
        $table->foreignId('school_id')->constrained('schools')->onDelete('cascade');
        $table->foreignId('user_id')->constrained('users')->onDelete('cascade');
        $table->set('type', ['Manager', 'Staff', 'Teacher', 'Student']);
        $table->softDeletes('deleted_at', 0);
        $table->timestamps();
});

注意:我的迁移文件基于laravel documentation,但出现此错误。

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

问题在于您的主键和外键列的类型不匹配。

您的主键列为UUID,外键列为BIGINT

更改以下内容可以解决该错误:

$table->foreignId('school_id')->constrained('schools')->onDelete('cascade');

$table->uuid('school_id')->constrained('schools')->onDelete('cascade');