Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create MyIsam table with a group auto_increment with Laravel migrations

Using Laravel Migrations, is there a way to create this an MyISAM table with a two-column primary key and an auto-increment in one of them?

CREATE TABLE animals (
    grp ENUM('fish','mammal','bird') NOT NULL,
    id MEDIUMINT NOT NULL AUTO_INCREMENT,
    name CHAR(30) NOT NULL,
    PRIMARY KEY (grp,id)
) ENGINE=MyISAM;

In this case the id AUTO_INCREMENT is done relative to the value of grp column. And you get something like this:

+--------+----+---------+
| grp    | id | name    |
+--------+----+---------+
| fish   |  1 | lax     |
| mammal |  1 | dog     |
| mammal |  2 | cat     |
| mammal |  3 | whale   |
| bird   |  1 | penguin |
| bird   |  2 | ostrich |
+--------+----+---------+
like image 665
Papa Lazzarou Avatar asked Oct 19 '25 13:10

Papa Lazzarou


1 Answers

Well, I managed to do it with two migrations 1. Create the table and assign the PK as usual to the two fields. 2. Create a new migration to modify and add the AUTO_INCREMENT attribute to the id column.

create_animals_table:

Schema::create('animals', function(Blueprint $table) {
    $table->engine = 'MyISAM';
    $table->enum('grp', ['fish', 'mammal', 'bird']);
    $table->unsignedBigInteger('id'); 
    $table->char('name', 30);

    $table->primary(['grp', 'id']);
});

add_auto_increment_to_animals_table:

Schema::table('animals', function ($table) {
    $table->bigIncrements('id')->unsigned()->change();
});
like image 78
Papa Lazzarou Avatar answered Oct 22 '25 19:10

Papa Lazzarou