无法添加外键

ih99xse1  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(256)

我试图将外键添加到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,我也这样做了,但错误仍然存在。这是我创建错误修复表的迁移脚本

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');
        ...
    });
}
6rqinv9w

6rqinv9w1#

尝试更改的迁移 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');
...
});
}

9w11ddsr

9w11ddsr2#

你应该试试这个:

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');
        ...
    });
}

相关问题