如何使用 Go-GORM 解决弱实体的重复列错误?

How to solve duplicate column error with weak entities using Go-GORM?

我正在使用 Gin、GORM 和 mySQL,我有两个具有复合主键的弱实体 like this

type FavoriteWord struct {
    WordID   uint `json:"word_ID" gorm:"type:INT NOT NULL;primaryKey;autoIncrement:false"`
    UserID   uint `json:"user_ID" gorm:"type:INT NOT NULL;primaryKey;autoIncrement:false"`
}

type FavoritePhrase struct {
    PhraseID uint `json:"phrase_ID" gorm:"type:INT NOT NULL;primaryKey;autoIncrement:false"`
    UserID   uint `json:"user_ID" gorm:"type:INT NOT NULL;primaryKey;autoIncrement:false"`
}

但是当使用 database.AutoMigrate(&FavoriteWord{}) Go 运行时抛出:

并且当使用 database.AutoMigrate(&FavoritePhrase{}) Go 运行时抛出:

Other questionsgorm.Model陈述同样的问题,但我根本没用过。

(最小)SQL 是:

CREATE TABLE IF NOT EXISTS `test`.`user`(
    `ID` INT AUTO_INCREMENT NOT NULL,
    PRIMARY KEY (`ID`)
);

CREATE TABLE IF NOT EXISTS `test`.`phrase`(
    `ID` INT AUTO_INCREMENT NOT NULL,
    `text` TEXT NOT NULL,
    PRIMARY KEY (`ID`)
);

CREATE TABLE IF NOT EXISTS `test`.`word`(
    `ID` INT AUTO_INCREMENT NOT NULL,
    `text` TEXT NOT NULL,
    PRIMARY KEY (`ID`)
);

CREATE TABLE IF NOT EXISTS `test`.`favorite_phrases`(
    `phrase_ID` INT NOT NULL,
    `user_ID` INT NOT NULL,
    FOREIGN KEY (`phrase_ID`) REFERENCES `test`.`phrase`(`ID`),
    FOREIGN KEY (`user_ID`) REFERENCES `test`.`user`(`ID`)
);

CREATE TABLE IF NOT EXISTS `test`.`favorite_words`(
    `word_ID` INT NOT NULL,
    `user_ID` INT NOT NULL,
    FOREIGN KEY (`word_ID`) REFERENCES `test`.`word`(`ID`),
    FOREIGN KEY (`user_ID`) REFERENCES `test`.`user`(`ID`)
);

实际上,自动迁移数据库时可能需要可选的 GORM column 标记。检查记录器(稍后解释),我看到 GORM 将我所有的单数 tables 复制为复数 tables,显然这是一个功能。

我已经设法解决了将 GORM 设置为单数命名 tables 的问题:

dsn := "user:password@tcp(localhost:3306)/db?charset=utf8mb4&parseTime=True&loc=Local"
database, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
    NamingStrategy: schema.NamingStrategy{
        SingularTable: true, // !!!
    },
})

并在每个结构中使用 GORM column 标签:

type FavoritePhrase struct {
    PhraseID uint   `json:"phrase_ID" gorm:"column:phrase_ID;type:INT NOT NULL;primaryKey;autoIncrement:false"`
    UserID   uint   `json:"user_ID" gorm:"column:user_ID;type:INT NOT NULL;primaryKey;autoIncrement:false"`
}

type FavoriteWord struct {
    WordID   uint   `json:"word_ID" gorm:"column:word_ID;type:INT NOT NULL;primaryKey;autoIncrement:false"`
    UserID   uint   `json:"user_ID" gorm:"column:user_ID;type:INT NOT NULL;primaryKey;autoIncrement:false"`
}

对于尝试调试此类错误的其他用户来说,一个很好的提示是使用记录器:

f, err := os.OpenFile("testlogfile", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
    log.Fatalf("error opening file: %v", err)
}
defer f.Close()

newLogger := logger.New(
    log.New(f, "\r\n", log.LstdFlags), // io writer
    logger.Config{
        SlowThreshold: time.Second, // Slow SQL threshold
        LogLevel:      logger.Info, // Log level
        Colorful:      true,        // Allow color
    },
)

dsn := "user:password@tcp(localhost:3306)/db?charset=utf8mb4&parseTime=True&loc=Local"
database, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
    Logger: newLogger,
})

//... automigrate & etc

并查询数据库与 GORM 记录的相同查询,以查看实际的 table 是否被 GORM 更改,或者它试图更改什么

SELECT column_name, is_nullable, data_type, character_maximum_length, numeric_precision, numeric_scale, datetime_precision FROM information_schema.columns WHERE table_schema = 'db' AND table_name = 'table';