[英]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();
});
我是新的 laravel,当我运行迁移时,在终端显示
SQLSTATE [HY000]:一般错误:1215 无法添加外键约束(SQL:alter table students
添加约束students_city_id_foreign
外键( city_id
)在删除级联时引用cities
( id
)
帮我修
您的问题出在代码顺序上。 您想为尚不存在的表创建外键。
试试这个:
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');
});
像这样,您首先创建两个表,然后设置外键。
如果您使用的是更新版本的 Laravel,则id
字段现在是unsignedBigInteger
字段。 因此,您应该执行以下操作:
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();
});
此外,请确保城市迁移在学生之前进行。
=>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.