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,当我运行migrate时,在终端显示
SQLSTATE[HY000]:一般错误:1215无法添加外键约束(SQL:更改表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');
});
像这样,首先创建两个表,然后设置外键。
如果您使用的是更新版本的Laravelid
字段,则现在是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.