不能添加外键

时间:2018-11-01 02:37:59

标签: php mysql laravel foreign-keys

我正在尝试将外键添加到laravel中的表中,并且此错误出现在我体内

In Connection.php line 664:

  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
  : alter table `bugFix` add constraint `bugfix_project_id_foreign` foreign k
  ey (`project_id`) references `Project` (`id`))


In Connection.php line 458:

  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint

我搜索了类似于ine的问题,每个人都要求将数据库引擎设置为InnoDB,但是我确实做了,但是错误仍然存​​在。这是我用于创建bugFix表的迁移脚本

public function up()
{
    Schema::create('bugFix', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        ...
        $table->unsignedInteger('project_id');
        ...
        $table->foreign('project_id')
          ->references('id')->on('Project');
        ...
    });
}

这是创建项目表的脚本

public function up()
{
    Schema::create('project', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        // Project document information
        $table->increments('id');
        ...
    });
}

2 个答案:

答案 0 :(得分:1)

您应该尝试以下操作:

public function up()
{
    Schema::create('bugFix', function (Blueprint $table) {
        $table->integer('project_id')->nullable()->unsigned();
        ...
        $table->foreign('project_id')
          ->references('id')->on('Project')->onDelete('cascade');
        ...
    });
}

答案 1 :(得分:0)

尝试更改unsigned integer declaration的迁移 并且表格名称应为正确的拼写Project => project

public function up()
{
    Schema::create('bugFix', function (Blueprint $table) {
        $table->engine = 'InnoDB';
        ...
        $table->integer('project_id')->unsigned();
        ...
        $table->foreign('project_id')
          ->references('id')->on('project');
        ...
    });
}