我知道gorm多对多关联会创建一个连接表,但如果我想要/需要一个包含附加字段的自定义连接表,该怎么办
下面是我的示例x1c 0d1x
我有两个模特
type Exercise struct {
gorm.Model
Name string `gorm:"not null" json:"name"`
Description string `gorm:"not null json:"description"`
}
type Workout struct {
gorm.Model
Name string `gorm:"not null" json:"name"`
CreatedAt time.Time `gorm:"not null" json:"created_at"`
}
如果我使用gorm多对多关联,它会创建一个exworkout_exercise连接表,但是我如何确保像reps和set这样的附加字段被填充。这是需要在控制器中完成的事情,而不是gorm真正处理的事情吗?我已经在Nodejs和sequelize中做过类似的事情,但对go和gorm世界来说真的是新事物。
3条答案
按热度按时间50pmv0ei1#
有点晚了党,但...我的目标是创造一些类似的,并花了一整天的时间后,它,并撞上了墙,退一步重新思考它...
经过一番沉思,许多游戏,和一个朋友的好建议,决定从一个稍微不同的Angular 来处理。
如果你换个Angular 来看,你可以把它“改写”成两个有一个(或属于一个)和两个一对多:
此外,在我的游戏中,我意识到多对多表的属性(列)在上面的模型中没有引用,所以它没有任何用处。
如果你把锻炼-锻炼看作是一种“一流”的模式,它开始变得更有意义,更有用:
总而言之,我的建议是:
它产生了下面的模式(我认为这是所需要的):
如果你想一想,只提取锻炼的练习而不提取附加属性是没有意义的。如果你只想得到锻炼的练习,你可以从中间模型中提取它 *:
toe950272#
我想如果你想在连接表中添加一个字段,你可以阅读关于自定义连接表的gorm文档
定义练习结构
定义锻炼结构
定义健身锻炼结构
自动迁移前设置连接
运行自动迁移
olmpazwi3#
many2many的标签值是您定义的关联表名的名称。并使用以下代码加载包含锻炼数据的练习。
如果你想加载锻炼数据,只需在Workout结构中添加many2many associate,例如: