thebigk
4 months ago

Migrations: Adding foreign_key when table is yet to be created?

Posted 4 months ago by thebigk

I'm creating two tables that reference each other's columns-

> create_conversations_table

$table->bigIncrements('id');
...
...
$table->unsignedBigInteger('last_message_id');
$table->timestamps();

and then I've the messages table -

> create_messages_table


$table->unsignedBigInteger('id');
$table->unsignedBigInteger('conversation_id');
...
...
$table->timestamps();

Now, I wish to have the following in my conversations table -

$table->foreign('last_message_id')->references('id')->on('messages')->onDelete('cascade');

and on messages table -

$table->foreign('conversation_id')->references('id')->on('conversations')->onDelete('cascade');

As of now, I can only have either of the two depending upon which migration runs first. Is there a way to do this? Or should I go for creating a separate migration that sets the foreign key references on these two tables?

What'd be your suggestion?

Please sign in or create an account to participate in this conversation.