如何修改Gorm多对多关联中间表列名以适配生产数据库?
解决Gorm多对多中间表列名匹配问题
完全可以通过调整Gorm的关联标签配置,直接让其适配生产库已有的中间表列名,无需手动创建中间表。具体修改方式如下:
修改结构体关联标签
在多对多关联字段的gorm标签中,添加joinForeignKey和joinReferences参数,分别指定当前模型、关联模型在中间表中的外键列名:
修改后的Playlist结构体
type Playlist struct { ID int32 `json:"id" gorm:"primaryKey;autoIncrement:true"` Status bool `json:"status" gorm:"not null;default:false"` CreatedAt time.Time `json:"createdAt" gorm:"column:created_at;autoCreateTime:milli;type:TIMESTAMP without time zone;default:now();not null"` UpdatedAt time.Time `json:"updatedAt" gorm:"column:updated_at;autoUpdateTime:milli;type:TIMESTAMP without time zone;default:now();not null"` Genres []Genre `json:"genres" gorm:"many2many:playlists_genres;joinForeignKey:playlistsId;joinReferences:genresId"` }
修改后的Genre结构体
type Genre struct { ID int32 `json:"id" gorm:"primaryKey;autoIncrement:true"` Name string `json:"name" gorm:"not null;type:varchar(255)"` Playlists []Playlist `json:"playlists" gorm:"many2many:playlists_genres;joinForeignKey:genresId;joinReferences:playlistsId"` }
参数说明
joinForeignKey:指定当前模型在中间表中的外键列名,比如Playlist结构体中对应中间表的playlistsIdjoinReferences:指定关联模型在中间表中的外键列名,比如Playlist结构体中对应Genre的genresId- 反向关联的Genre结构体需要调换两个参数的取值,因为当前模型变为Genre,对应中间表的
genresId作为外键,关联模型Playlist对应playlistsId
配置完成后,Gorm会自动适配生产库中已存在的playlists_genres表,正确映射playlistsId和genresId字段,无需额外手动创建中间表。
内容的提问来源于stack exchange,提问作者Marcos Knopp
相关产品推荐
相关产品推荐

