Home > Back-end >  How to add a comment on an index in a Laravel migration?
How to add a comment on an index in a Laravel migration?

Time:01-18

In my Laravel 9 application with a MySQL database, I am trying to add a comment to a unique contraint with a migration file. According to the Laravel documentation adding comments is only allowed on column modifiers (thus no support for the unique constraint). However, when I look at the MySQL documentation I see MySQL does support it.

My following code will silently ignore the comment on the unique constraint:

Schema::create('customer_order', function (Blueprint $table) {
    $table->id();
    $table->unsignedInteger('customer_id');
    $table->unsignedInteger('order_id');

    $table->foreign('customer_id')->references('id')->on('customer');
    $table->foreign('order_id')->references('id')->on('orders');
    $table->unique(['customer_id'])->comment('To enforce this is table is used as a one to many relationship.');
    $table->unique(['customer_id', 'order_id']);
}

Since it appears that Laravel does not support adding comments on indexes (like a unique constraint), is there a workaround?

p.s. I am aware I strictly do not need a pivot table in this situation. Please just assume I need the pivot table setup for some historical or technical reason.

CodePudding user response:

Use DB::statement("ALTER TABLE

Schema::create('customer_order', function (Blueprint $table) {
    $table->id();
    $table->unsignedInteger('customer_id');
    $table->unsignedInteger('order_id');
    $table->foreign('customer_id')->references('id')->on('customer');
    $table->foreign('order_id')->references('id')->on('orders');
    $table->unique(['customer_id', 'order_id']);
    DB::statement("ALTER TABLE customer_order ADD CONSTRAINT unique_customer_id UNIQUE (customer_id) COMMENT 'To enforce this is table is used as a one to many relationship.';");
});
  • Related