laravel - 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() 但仍然没有工作!任何帮助,将不胜感激!
解决方案
我想我找到了问题...
如果你真的想为非主键创建一个外键,它必须是一个对其有唯一约束的列。
所以你必须在
$table->integer('vendor_id')->unsigned()->nullable()->unique();
请参见:
推荐阅读
- python-3.x - 如何将大列表拆分为由特定标记分隔的小子列表
- vue.js - 为什么我的组件没有刷新页面就不会更新?
- flutter - 如何在 Flutter 中将文本小部件彼此相邻包装
- c# - 从网络路径而不是应用程序路径显示文件
- python - 我想打印 Python 地图列表元素
- python - TypeError:'int' 对象在 Tkinker 电影预订 GUI 中不可下标
- python - 使用 PIL、plt、numpy 绘制直方图时出错
- swift - Swift JsonDecoder Networking Hi 未打印
- ruby-on-rails - 在 Rails 中使用局部变量(添加占位符)时出现问题?
- c# - 查找数组中的异常值?