简体   繁体   English

1215 无法在 laravel 中添加外键约束

[英]1215 Cannot add foreign key constraint in laravel

Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->integer('age')->unsigned();
        $table->integer('city_id')->unsigned();
        $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
        $table->timestamps();
});
Schema::create('cities', function (Blueprint $table) {
        $table->id();
        $table->text('name');
        $table->timestamps();
});

i'm new laravel, when i run migrate, in terminal show我是新的 laravel,当我运行迁移时,在终端显示

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table students add constraint students_city_id_foreign foreign key ( city_id ) references cities ( id ) on delete cascade) SQLSTATE [HY000]:一般错误:1215 无法添加外键约束(SQL:alter table students添加约束students_city_id_foreign外键( city_id )在删除级联时引用citiesid

help me fix帮我修

Your problem is on the order of the code.您的问题出在代码顺序上。 You want to make a foreign key to a table which is not yet exists.您想为尚不存在的表创建外键。

Try this instead:试试这个:

Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->integer('age')->unsigned();
        $table->integer('city_id')->unsigned();
        $table->timestamps();
});

Schema::create('cities', function (Blueprint $table) {
        $table->id();
        $table->text('name');
        $table->timestamps();
});

Schema::table('students', function(Blueprint $table) {
        $table->foreign('city_id')->references('id')->on('cities')->onDelete('cascade');
    });

Like this, you first creates both tables, and after that you set the foreign key.像这样,您首先创建两个表,然后设置外键。

If you are using more recent version of Laravel id fields are now unsignedBigInteger field.如果您使用的是更新版本的 Laravel,则id字段现在是unsignedBigInteger字段。 So you should do something like:因此,您应该执行以下操作:

Schema::create('cities', function (Blueprint $table) {
        $table->id();
        $table->text('name');
        $table->timestamps();
});
Schema::create('students', function (Blueprint $table) {
        $table->id();
        $table->integer('age')->unsigned();
        $table->foreignId('city_id')->constrained()->onDelete('cascade');
        $table->timestamps();
});

Also, make sure the cities migration is running before students.此外,请确保城市迁移在学生之前进行。

=>your cities migration first create then after students migration create because your city_id foreign key reference to the cities table laravel migration check order and order wise migration run so first cities migration run(cities table create) then students migration run.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM