i am beginner programmer of laravel.i am creating a simple warehouse management system in laravel 11.when i tried to migrate and tables and assign the Foreign keys i ran into the problem with Foreign key constraint is incorrectly . what i tried the migration file and full error i attached below.
Error
SQLSTATE[HY000]: General error: 1005 Can't create table `dbwarehourse`.`order_products` (errno: 150 "Foreign key constraint is incorrectly formed") (Connection: mysql, SQL: alter table `order_products` add constraint `order_products_order_id_foreign` foreign key (`order_id`) references `orders` (`id`))
Product table
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string('productcode');
$table->foreignId('category_id')->constrained('categories');
$table->string('productname');
$table->decimal('price', 8, 2);
$table->integer('stock');
$table->integer('stock_level'); // Add this line
$table->boolean('status')->default(0);
$table->timestamps();
});
Order table
Schema::create('orders', function (Blueprint $table) {
$table->id();
$table->interger('invoicenumber');
$table->foreignId('client_id')->constrained('clients');
$table->decimal('total_amount', 10, 2);
$table->boolean('status')->default(0);
$table->timestamps();
});
Order_products
Schema::create('order_products', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained('products');
$table->foreignId('order_id')->constrained('orders');
$table->integer('quantity');
$table->decimal('price', 8, 2);
$table->timestamps();
});
2
The error you are getting is for assigning order_id
foreign_key in order_products
table.
Though the syntax is correct but still there might be some nameing convention issue.I have also face similar situation in my own case.And I found this following solutions helpful.
Since the error says..
(errno: 150 “Foreign key constraint is incorrectly formed”)
(Connection: mysql, SQL: alter tableorder_products
add constraint
order_products_order_id_foreign
foreign key (order_id
) references
orders
(id
))
So avoid using constrained()
method and instead explicitely define Foreign Key Constraints
like this in Order_products
schema.
Schema::create('order_products', function (Blueprint $table) {
$table->id();
$table->foreignId('product_id')->constrained('products');
$table->unsignedBigInteger('order_id');
//define foreign key Constraint
$table->foreign('order_id')->references('id')->on('orders')->onDelete('cascade');
$table->integer('quantity');
$table->decimal('price', 8, 2);
$table->timestamps();
});
Try this ,I think it will resolve the issue.
In case you face any issue let me know.