首页 > 解决方案 > Laravel 5.3 迁移:1215 无法添加外键约束

问题描述

我正在使用 Laravel 5.3 并且正在尝试创建 FK,但是当我使用 artisan 迁移我的表时,我收到以下错误:

  [Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table `topic_video` add constraint `topic_video_vendor_id_foreign` foreign key (`vendor_id`) references `vendors` (`id`))



  [Doctrine\DBAL\Driver\PDOException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint



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

我已经为不同的 laravel 版本在 SOF 上尝试了多种解决方案,但它们都不起作用。

这是我的 topic_video 表(InnoDB)

在此处输入图像描述

这是一个古老而大的项目,因为我没有为它迁移,只有对于我们有迁移的新表。所以我创建了一个供应商(MyISAM)

Schema::create('vendors', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('channel_url');
            $table->timestamps();
        });

然后我将上述迁移的 FK 添加到 topic_video 表中。

Schema::table('topic_video', function (Blueprint $table) {
            $table->integer('vendor_id')->unsigned()->nullable();
            $table->foreign('vendor_id')->references('id')->on('vendors');
        });

我试过没有 unsigned(),没有 nullable() 但仍然没有工作!任何帮助,将不胜感激!

标签: laravellaravel-5migrationdatabase-migration

解决方案


我想我找到了问题...

如果你真的想为非主键创建一个外键,它必须是一个对其有唯一约束的列。

所以你必须在

$table->integer('vendor_id')->unsigned()->nullable()->unique();

请参见:

https://stackoverflow.com/a/18435114/10573560

https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175464(v=sql.105)?redirectedfrom=MSDN


推荐阅读