0
votes

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)

enter image description here

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!

2
are you sure the vendors 's migration comes before topic_video migration in your migrations folder?OMR
topic_video deosn't have a migration, it was created through database long time ago approx 10 years. As i have mentioned, only the new tables which we are creating in future has migration, Today i have created vendors folders migration and added it, then tried to created topic_video migration for foreign key above.Asfandyar Khan
and my topic_video migration for adding fk comes after vendors table creation migrationAsfandyar Khan

2 Answers

0
votes

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

0
votes

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