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)
Schema::create('categories', function (Blueprint $table) { $table->id(); $table->string('name'); $table->string('slug'); $table->timestamps(); });
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->integer('category_id')->unsigned(); $table->foreign('category_id')->nullable()->references('id')->on('categories'); $table->string('title')->nullable(); $table->timestamps(); }); }
class Category extends Model { use HasFactory; protected $table = 'categories'; protected $guarded = []; public function posts(){ return $this->hasMany(Post::class); } }
class Post extends Model { use HasFactory; protected $guarded = []; public function category(){ return $this->belongsTo(Category::class); } }
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
Schema::create('categories', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name'); $table->string('slug'); $table->timestamps(); });
Post Table
Schema::create('posts', function (Blueprint $table) { $table->id(); $table->bigInteger('category_id')->unsigned()->nullable(); $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade'); $table->string('title')->nullable(); $table->timestamps(); });
Note: You should make sure, your Category Table migration is running before Post Table migration.