Pivot table migration not using custom table name

47 views Asked by At

I'm trying to make a pivot table in Laravel but I'm using spanish terms for the names:

products - productos | distributors - distribuidores

here is part of the migrations for each:

distributors migration:

Schema::create('distribuidores', function (Blueprint $table) {
            $table->id();
            $table->string("nombre");
            $table->timestamps();
        });
    }

products migration:

Schema::create('productos', function (Blueprint $table) {
            $table->id();
            $table->string("nombre");
            $table->decimal("precio",10,2);
            $table->foreignId("categoria_id")->constrained()->onDelete("cascade");
            $table->timestamps();
        });

pivot table distribuidor_producto_table migration

Schema::create('distribuidor_producto', function (Blueprint $table) {
            $table->id();
            $table->foreignId("distribuidor_id")->constrained()->onDelete("cascade");
            $table->foreignId("producto_id")->constrained()->onDelete("cascade");
            $table->timestamps();
        });

I also added the proper table name in Distribuidor model:

protected $table = 'distribuidores';

But I get the following error with the pivot table migration:

SQLSTATE[HY000]: General error: 1005 Can't create table `tienda`.`distribuidor_producto` (errno: 150 "Foreign key constrainhowt is incorrectly formed") (Connection: mysql, SQL: alter table `distribuidor_producto` add constraint `distribuidor_producto_distribuidor_id_foreign` foreign key (`distribuidor_id`) references `distribuidors` (`id`) on delete cascade)

As you can see after references it mentions distribuidors which I understand is how Laravel originally called the migration based on model Distribuidor

1

There are 1 answers

0
Kaveh Mohammadi On BEST ANSWER

Model Configuration: Ensure that your Distribuidor model specifies the custom table name correctly:

protected $table = 'distribuidores';

Migration Configuration: In your pivot table migration, explicitly specify the custom table names for foreign key constraints:


$table->foreignId('distribuidor_id')->constrained('distribuidores')->onDelete('cascade');
$table->foreignId('producto_id')->constrained('productos')->onDelete('cascade');

Foreign Key Types: Ensure that the types of foreign keys match the types of the referenced primary keys.

Migration Order: Ensure that migrations for distribuidores and productos tables run before the pivot table migration.

After making these adjustments, run php artisan migrate:fresh to reset migrations and try again. This should resolve the issue.