![](/img/trans.png)
[英]Laravel Migrations - General error: 1215 Cannot add foreign key constraint
[英]Laravel Migrations: Cannot add foreign key constraint
我试图通过Laravel Migrations将外键约束添加到我的数据库表中,但是我总是收到这样的错误:
Illuminate\Database\QueryException :
SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint
(SQL: alter table `tasks` add constraint `tasks_task_list_id_foreign` foreign key (`task_list_id`) references `task_lists` (`id`))
tasks
表的迁移如下所示:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTasksTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('tasks', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->integer('task_list_id')->unsigned()->index();
$table->string('task');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->foreign('task_list_id')->references('id')->on('task_lists');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('tasks');
}
}
这就是task_lists
表:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTaskListsTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('task_lists', function (Blueprint $table) {
$table->increments('id');
$table->integer('user_id')->unsigned()->index();
$table->string('name');
$table->timestamps();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('task_lists');
}
}
我无法解决问题,非常感谢您提供任何帮助。
先感谢您!
您必须检查迁移顺序。 显然,您必须先执行de Users表迁移,然后再执行Tasks表迁移。 如果问题仍然存在,请尝试在up()方法内部以及(Schemma :: create)之后进行如下操作:
Schema::table('task_lists', function($table){
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.