Skip to content
Advertisement

SQLSTATE[HY000]: General error: 1005 Can’t create table `school`.`posts` (errno: 150 “Foreign key constraint is incorrectly formed”)

before everything, I tried hard many websites and forums to solve this problem until these posts related to this problem in StackOverflow, but I can’t solve the problem. I want to create to one to many relationship between Post and Category model but I get that error code.

SQLSTATE[HY000]: General error: 1005 Can’t create table school.posts (errno: 150 “Foreign key constraint is incorrectly formed”) (SQL: alter table posts add constraint posts_category_id_foreign foreign key (category_id) references categories (id) on delete cascade)

JavaScript
JavaScript
JavaScript
JavaScript

please help me I appreciate your help.

Advertisement

Answer

Your foreign_key field and your id should be of the same type, for example, if categories.id is bigIncrements, your foreign_key inside your Post table also should be bigInteger.

Category Table

JavaScript

Post Table

JavaScript

Note: You should make sure, your Category Table migration is running before Post Table migration.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement