[英]Laravel 5.3 Migration: 1215 Cannot add foreign key constraint
我正在使用 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() 但仍然没有工作! 任何帮助,将不胜感激!
尝试这个..
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 迁移创建之前
我想我找到了问题所在...
如果你真的想为非主键创建一个外键,它必须是一个对其有唯一约束的列。
所以你必须在
$table->integer('vendor_id')->unsigned()->nullable()->unique();
请参见:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.