我使用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(),但还是不行! 任何帮助将被感激!
试试这个...
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();
请看。