[英]Laravel 5.3 Migration: 1215 Cannot add foreign key constraint
I'm using Laravel 5.3 and I'm trying to create FK, however when I migrate my table using artisan I'm getting the following error:我正在使用 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
I have tried multiple solutions on SOF for different laravel versions but none of them work.我已经为不同的 laravel 版本在 SOF 上尝试了多种解决方案,但它们都不起作用。
This is my topic_video table (InnoDB)这是我的 topic_video 表(InnoDB)
This is an old and big project, as I don't have migrations for it, only for new tables we have migrations.这是一个古老而大的项目,因为我没有为它迁移,只有对于我们有迁移的新表。 So I have created a vendors (MyISAM)所以我创建了一个供应商(MyISAM)
Schema::create('vendors', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('channel_url');
$table->timestamps();
});
Then I have add FK of above migration to topic_video table.然后我将上述迁移的 FK 添加到 topic_video 表中。
Schema::table('topic_video', function (Blueprint $table) {
$table->integer('vendor_id')->unsigned()->nullable();
$table->foreign('vendor_id')->references('id')->on('vendors');
});
I have tried without unsigned(), without nullable() but still didn't work!我试过没有 unsigned(),没有 nullable() 但仍然没有工作! Any help would be appreciated!任何帮助,将不胜感激!
try this..尝试这个..
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');
});
}
and make sure the vendors migration create is before the topic_video migration create并确保供应商迁移创建在 topic_video 迁移创建之前
i think i have found the problem...我想我找到了问题所在...
If you really want to create a foreign key to a non-primary key, it MUST be a column that has a unique constraint on it.如果你真的想为非主键创建一个外键,它必须是一个对其有唯一约束的列。
so you must add 'unique' constraint on所以你必须在
$table->integer('vendor_id')->unsigned()->nullable()->unique();
please see:请参见:
https://stackoverflow.com/a/18435114/10573560 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 https://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175464(v=sql.105)?redirectedfrom=MSDN
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.