I have problem with Laravel migrations. I want to make a relationship between two tables but
I am getting error General error: 1005 Can’t create table
eshopper
.prices
(errno: 150 "Foreign key constraint is incorrectly
formed") (SQL: alter tableprices
add constraintpri ces_product_id_foreign
foreign key (product_id
) references
products
(id
) .
Here is my code. Tables are prices and products.
Prices
public function up()
{
Schema::create('prices', function (Blueprint $table) {
$table->id();
$table->float('amount');
$table->unsignedBigInteger('product_id')->unsigned()->index();
$table->foreign('product_id')->references('id')->on('products')->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
});
}
Products
public function up()
{
Schema::create('products', function (Blueprint $table) {
$table->id();
$table->string("title",100);
$table->text("description");
$table->timestamps();
});
}
NOTE: In my migrations products table is under prices table, I know that the first created table is prices than products and that is error.
My question is do I have to put products frst or I can keep same layout(prices first, than products) and change something in code?
3
Answers
it happens because the
product_id
field type is different from theid
field in the products table, try this in the products migration file:Instead of putting the constraints inside the migration file of
price
you can put it inside the migration file ofproducts
. Since it will create theprices
table first before theproducts
the constraints will not be created because theproducts
table is not yet created.Short answer is that you MUST put
products
first beforeprices
. If the whole code is still in development and have yet to get deployed, then the easiest solution is to rename theproducts
table migration so that it has older timestamp than theprices
migration has.