Laravel Eloquent creates a composite key that uses auto-increments

I have a migration as shown below

        $table->increments('id');
        $table->integer('order_num');
        $table->timestamps();

      

The primary key must be a combination of id and order_num. If I put the code below it says that I am trying to add 2 primary keys (because the increments are also the primary key). Is there a way to tell the eloquence that I'm trying to put them together.

        $table->primary(['course_id', 'order_num']);

      

+3


source to share


1 answer


I am assuming you are using MySQL .

First of all, the default InnoDB MySQL server does not allow composite primary keys, in which one of the fields will be auto-incrementing. The engine that MyISAM enables this , so the first thing you need to do is change the engine for the table.

This can be done by adding the following to the table definition:

$table->engine = 'MyISAM';

      

The next question you need to address is the fact that Laravel's schema builder assumes that the autoincrement column you specified is your primary key. This means that you are already getting a message about an existing primary key - Laravel has already made the id field the primary key.

To solve this problem, you need to declare the id field as a regular integer column, define all other columns, and finally declare a composite primary key. It might look like this:



$table->integer('id');
$table->integer('order_num');
$table->timestamps();
$table->primary(['course_id', 'order_num']);

      

Thus, you have created a composite primary key. The only thing missing is the autoincrement attribute on the id column . Laravel's schema designer does not provide methods to modify existing columns, so you will need to run raw SQL queries. Required request:

DB::statement('ALTER TABLE my_table MODIFY id INTEGER NOT NULL AUTO_INCREMENT');

      

To summarize, your upward () migration method might look like this:

public function up()
{
  Schema::create('my_table', function (Blueprint $table) {
    $table->engine = 'MyISAM';

    $table->integer('id');
    $table->integer('order_num');
    $table->timestamps();
    $table->primary(['course_id', 'order_num']);
  });

  DB::statement('ALTER TABLE my_table MODIFY id INTEGER NOT NULL AUTO_INCREMENT');
}

      

+5


source







All Articles