Skip to content

How to dynamically create table names #7549

@hamwong233

Description

@hamwong233

Your Question

When using db.Table(tableName).AutoMigrate(&Model{}) to dynamically create tables, the indexes defined in the model struct are not created in the actual database table.

This causes issues when the model has unique indexes or other constraints, which are silently ignored when using dynamic table creation.

type Post struct {
  ID        uint   `gorm:"primaryKey"`
  OriginID  string `gorm:"uniqueIndex;size:255"`
  Title     string
}

When I run:

db.Table("post_2025").AutoMigrate(&Post{})

The table is created, but the unique index on OriginID is missing.

Expected answer

How to dynamically create table names

Metadata

Metadata

Assignees

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions