【发布时间】: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