Check the order of your migrations. If your migrate command is trying to make the posts table before the post_categories 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.
errno: 150 "Foreign key constraint is incorrectly formed"
I have many to one relation from Category to Post, and following are from respective migrations:
Posts: public function up() { Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->string('body')->nullable();
$table->integer('cat_id')->unique()->nullable();
$table->foreign('cat_id')
->references('id')->on('post_categories')
->onDelete('cascade');
$table->dateTime('event_at')->nullable();
$table->timestamps();
});
Post Categories:
public function up() { Schema::create('post_categories', function (Blueprint $table) {
$table->increments('id')->unsigned()->unique();
$table->string('cat_name');
$table->timestamps();
});
}
}
Models: Post: class Post extends Model {
use SearchableTrait;
protected $searchable = [
'columns' => [
'posts.title' => 10,
'posts.body' => 5,
]
];
public function postcategory() {
return $this->belongsTo(PostCategory::class);
}
}
Post_Category: class PostCategory extends Model { public function posts() {
return $this->hasMany(Post::class);
}
}
I keep getting this error message when i try migrating(php artisan migrate):
[Illuminate\Database\QueryException]
SQLSTATE[HY000]: General error: 1005 Can't create table artgallery.#sql-36c4_160 (errno: 150 "Foreign key constraint is incorrectly formed") (SQL: alter table posts add constraint pos ts_cat_id_foreign foreign key (cat_id) references post_categories (id) on delete cascade)
[PDOException]
SQLSTATE[HY000]: General error: 1005 Can't create table artgallery.#sql-36c4_160 (errno: 150 "Foreign key constraint is incorrectly formed")
Please guide where I could be committing mistake and what is the solution.
Please or to participate in this conversation.