首页 文章

`gorm`忽略`sql:“index”`标签

提问于
浏览
1

为什么 gorm 忽略 sql:"index" 标签?没有创建索引 .

这里使用的数据库是PostgreSQL(导入 _ "github.com/lib/pq" ) . 使用了这个 Model 结构(因为默认 gorm.Model 使用自动增量编号 - serial - 作为主键,我想自己设置 id ):

type Model struct {
    ID        int64 `sql:"type:bigint PRIMARY KEY;default:0"`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time `sql:"index"`
}

其中一个实际模型是:

type TUHistory struct {
    Model

    TUID        int64  `json:"tu_id,string" gorm:"column:tu_id" sql:"index"`
}

func (x *TUHistory) TableName() string {
    return "tu_history"
}

该表由 db.CreateTable(&TUHistory{}) 创建,除索引外,它正确创建表 .

作为临时工作,我做 db.Model(&TUHistory{}).AddIndex("ix_tuh_tu_id", "tu_id") 来创建索引 .

1 回答

  • 2

    根据我的经验,db.CreateTable只创建表及其字段 . 最好将AutoMigrate功能与要迁移的模型结构一起使用:

    db, err := gorm.Open("postgres", connectionString)
    ...
    // error checking
    ...
    
    db.AutoMigrate(&Model)
    

    此外,我尝试自动迁移您发布的模型并收到错误消息,说明不允许使用多个主键,因此我将模型更改为:

    type Model struct {
        Id        int64 `sql:"type:bigint;default:0"`
        CreatedAt time.Time
        UpdatedAt time.Time
        DeletedAt *time.Time `sql:"index"`
    }
    

    并且AutoMigration创建了所有PK和索引就好了 .

    Edit:

    检查GORM的自述文件,在example上,电子邮件结构如下:

    type Email struct {
        ID      int
        UserID  int     `sql:"index"` // Foreign key (belongs to), tag `index` will create index for this field when using AutoMigrate
        Email   string  `sql:"type:varchar(100);unique_index"` // Set field's sql type, tag `unique_index` will create unique index
        Subscribed bool
    }
    

    请注意UserId字段上的注释,说明它将在使用AutoMigrate时创建索引 .

    此外,值得一看的是AutoMigrate如何完成它的工作:

    // Automating Migration
    db.AutoMigrate(&User{})
    db.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&User{})
    db.AutoMigrate(&User{}, &Product{}, &Order{})
    // Feel free to change your struct, AutoMigrate will keep your database up-to-date.
    // AutoMigrate will ONLY add *new columns* and *new indexes*,
    // WON'T update current column's type or delete unused columns, to protect your data.
    // If the table is not existing, AutoMigrate will create the table automatically.
    

相关问题