Home > Software engineering >  how can I use the same foreign key twice in a single table?
how can I use the same foreign key twice in a single table?

Time:05-03

I came across a problem. So I have this migration in Laravel:

    {
        Schema::create('transfers', function (Blueprint $table) {
            $table->id();
            $table->foreignId('from_inventory_id')->constrained();
            $table->foreignId('to_inventory_id')->constrained();
        });
    }

What I am trying to do is to transfer products from an inventory to another. The problem is, if I name them the way I did above, Laravel won't recognize them as foreign keys because they have to be 'inventory_id', but I also can't have two columns named the same.

How can I name them whatever I want and apply to them the same foreign key?

CodePudding user response:

You should use the old syntax:

$table->unsignedBigInteger('from_inventory_id');
$table->foreign('from_inventory_id')->references('id')->on('inventories');
$table->unsignedBigInteger('to_inventory_id');
$table->foreign('to_inventory_id')->references('id')->on('inventories');
  • Related