Home > database >  laravel set postgresql identity column in migration
laravel set postgresql identity column in migration

Time:09-30

laravel $table->id() will set default nextval('tablename_id_seq'::regclass)

how to set GENERATED BY DEFAULT AS IDENTITY

CREATE TABLE color (
    color_id INT GENERATED BY DEFAULT AS IDENTITY,
    color_name VARCHAR NOT NULL
);

CodePudding user response:

To quote from the index modifiers table in the current documentation regarding migrations:

->generatedAs($expression) Create an identity column with specified sequence options (PostgreSQL).

The following code

Schema::create('color', function (Blueprint $table) {
    $table->mediumInteger('color_id')->generatedAs();
    $table->string('color_name');
});

generates

create table "color" (
  "color_id" integer generated by default as identity not null,
  "color_name" varchar(255) not null
)

If you add ->nullable() between mediumInteger('color_id') and generatedAs(), the color_id column is instead:

"color_id" integer generated by default as identity null
  • Related