akshay dighe
akshay dighe

Reputation: 13

cant create table in laravel 5.5 using migration because of foreign key fail

I get the following error when I run the migration command

SQLSTATE[HY000]: General error: 1005 Can't create table test.#sql-644_119 (errno: 150 "Foreign key constraint i s incorrectly formed") (SQL: alter table show_packages add constraint show_packages_package_id_foreign foreign key (package_id) references rent_package_no (id))

these are my table enter image description here

How can I fix it ?

Upvotes: 0

Views: 190

Answers (2)

Prashant Prajapati
Prashant Prajapati

Reputation: 1015

Migration order matter's here ensure that your foreign tables(rent_package_no & rent_lend_categories) is created before running this migration

Try using the below code:

Schema::create('show_packages', function(Blueprint $table) { 
    $table - > increments('id');
    $table - > integer('pack_id') - > unsigned();
    $table - > integer('cat_id') - > unsigned();
    $table - > timestamps();
    $table - > foreign('pack_id') - > references('id') - > on('rent_package_no')->onUpdate('cascade')->onDelete('cascade');
    $table - > foreign('cat_id') - > references('id') - > on('rent_lend_categories')->onUpdate('cascade')->onDelete('cascade'); 
});

Upvotes: 2

Illia Yaremchuk
Illia Yaremchuk

Reputation: 2025

Check the order of your migrations. If your migrate command is trying to make the rent_package_no table before the show_packages table this will occur with MySQL. It seems to go in order of date, oldest to newest. In other words, the cat_id on the the table it is trying to reference should exist.

Upvotes: 0

Related Questions