【问题标题】:Laravel 5.3 Migration: 1215 Cannot add foreign key constraintLaravel 5.3 迁移:1215 无法添加外键约束
【发布时间】:2020-09-21 06:00:25
【问题描述】:

我正在使用 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

我在 SOF 上针对不同的 laravel 版本尝试了多种解决方案,但没有一个可以工作。

这是我的 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() 但还是不行!任何帮助将不胜感激!

【问题讨论】:

  • 您确定 vendor 的迁移在您的迁移文件夹中的 topic_video 迁移之前进行吗?
  • topic_video 没有迁移,它是在大约 10 年前通过数据库创建的。正如我所提到的,只有我们将来创建的新表才有迁移,今天我创建了供应商文件夹迁移并添加了它,然后尝试为上面的外键创建 topic_video 迁移。
  • 而我添加 fk 的 topic_video 迁移是在供应商表创建迁移之后进行的

标签: laravel laravel-5 migration database-migration


【解决方案1】:

试试这个..

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

并确保供应商迁移创建在 topic_video 迁移创建之前

【讨论】:

  • topic_video 表已经有 id $table->increments('id'); 这是主键,它也有数千条记录。
  • 算上你提供了两个表的完整列列表
  • 我上面已经提供了,看上面topic_video表的截图,vendors表也已经提供了迁移。
  • 这个 sol 已经尝试过了,但没有成功,供应商迁移在 topic_video 之前进行
【解决方案2】:

我想我找到了问题...

如果您确实想为非主键创建外键,则它必须是对其具有唯一约束的列。

所以你必须在

上添加“唯一”约束
$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

【讨论】:

  • 基本上我将供应商的 id 作为 FK 添加到 topic_video,为什么我必须更改 topic_video 的 PK 中的任何内容?
  • 终于,...我已经更新了我的答案,请检查一下
猜你喜欢
  • 2019-07-31
  • 2021-03-29
  • 2017-09-06
  • 2021-06-18
  • 2020-07-08
  • 2019-07-27
  • 2019-03-24
  • 2017-03-27
  • 1970-01-01
相关资源
最近更新 更多