whjvdijk's avatar

Multiple relations to a foreign table

I have a table of Vendors. And I have a table of Equipment. I need multiple relations from the equipment to the vendor table (Producer, Supplier, Maintenance by).

When using: $table->foreignIdFor(Vendor::class);

I can only specify on relation on the Vendor table. And it won't accept 3 of these lines. How should I solve this issue? I assume this is possible? A pivot table doesn't feel like a good solution, since it's a fix amount of 3 relations. Using phpMyAdmin it's easy to create these relations, but how would I do that in my migration file?

This problem also arises on a customer table. The customer has a delivery address and a postal address. Both adresses have a country specified. So i need 2 different relations to the Country table from the Customer table.

0 likes
3 replies
martinbean's avatar
Level 80

@whjvdijk You can create multiple foreign key columns pointing to the same table:

Schema::table('customers', function (Blueprint $table) {
    $table->id();
    $table->foreignId('billing_address_id')->constrained('addresses');
    $table->foreignId('shipping_address_id')->constrained('addresses');
    // And any other columns...
});
Schema::table('equipment', function (Blueprint $table) {
    $table->id();
    $table->foreignId('producer_id')->constrained('vendors');
    $table->foreignId('supplier_id')->constrained('vendors');
    $table->foreignId('maintainer_id')->constrained('vendors');
    // And any other columns...
});

Docs: https://laravel.com/docs/11.x/migrations#foreign-key-constraints

1 like

Please or to participate in this conversation.