登录
首页 >  Golang >  Go问答

解决Go-GORM中弱实体重复列错误的方法

来源:stackoverflow

时间:2024-02-20 13:54:26 355浏览 收藏

知识点掌握了,还需要不断练习才能熟练运用。下面golang学习网给大家带来一个Golang开发实战,手把手教大家学习《解决Go-GORM中弱实体重复列错误的方法》,在实现功能的过程中也带大家重新温习相关知识点,温故而知新,回头看看说不定又有不一样的感悟!

问题内容

我正在使用 gin、gorm 和 mysql,我有两个具有复合主键的弱实体,如下所示:

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 运行时抛出:

  • 错误 1060:列名“user_id” 重复。
  • 更改表 favorite_words 添加 user_id varchar(191) (不知道为什么它在声明为 uint 时尝试将 user_id 键入为 varchar(191))

当使用 database.automigrate(&favoritephrase{}) go 运行时抛出:

  • 错误 1060:列名“user_id” 重复。
  • alter table favorite_phrases 添加phrase_id bigint unsigned

其他问题使用 gorm.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 将我所有的单数命名表复制为复数命名表,显然这是一个功能。

我已经成功解决了设置 gorm 以单数命名表的问题:

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 记录的相同查询,以查看 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';

理论要掌握,实操不能落!以上关于《解决Go-GORM中弱实体重复列错误的方法》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>