简体   繁体   中英

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:

  [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.

This is my topic_video table (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)

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.

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! 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

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://docs.microsoft.com/en-us/previous-versions/sql/sql-server-2008-r2/ms175464(v=sql.105)?redirectedfrom=MSDN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM