登录
首页 >  Golang >  Go问答

Gorm 协会多对多

来源:stackoverflow

时间:2024-03-18 22:51:29 410浏览 收藏

GORM 多对多关联通常会创建一个联接表,但如果需要一个带有附加字段的自定义联接表,则无法直接实现。本文介绍了一种替代方法,将多对多关系拆分为两个“有一”和两个一对多关系,从而创建一个“一流”的中间模型。这种方法允许在中间模型中添加额外的属性,例如次数和组数,并通过预加载功能轻松访问关联数据。

问题内容

我知道 gorm 多对多关联会创建一个联接表,但是如果我想要/需要一个带有附加字段的自定义联接表怎么办

我的例子如下

所以我有两个 gorm 模型

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 多对多关联,它将创建一个锻炼锻炼连接表,但我将如何确保填写其他字段(例如次数和组数)。这是需要在控制器中完成的事情,而不是真正由 gorm 处理的事情。我已经用 nodejs 和 sequelize 做了类似的事情,但对于 go 和 gorm 世界来说确实是新的。


解决方案


参加聚会有点晚了,但是......我的目标是创造类似的东西,在花了一整天的时间之后,碰壁了,退后一步重新思考......

经过一番深思熟虑,考虑了很多游戏以及朋友的良好建议,我们决定从稍微不同的角度进行处理。

如果您以不同的方式看待它,您可以将其“改写”为两个“有一”(或属于“属于”)和两个一对多,而不是多对多:

  • 锻炼有多种锻炼方式
  • 锻炼有很多锻炼活动
  • workout-exercise 包含锻炼和一项练习

此外,在我的游戏过程中,我意识到多对多表的属性(列)没有在上面模型中的任何地方引用,因此它无论如何都没有用。

如果您将锻炼-锻炼视为“一流”模型,那么它开始变得更有意义并且变得更有用:

  • 您可以创建练习 - 它是一种静态资源池
  • 您可以创建锻炼
  • 然后,您可以使用锻炼-锻炼模型将练习填充到锻炼中。

总而言之,我的建议如下:

type exercise struct {
    gorm.model
    name        string `gorm:"not null" json:"name"`
    description string `gorm:"not null" json:"description"`
    workouts    []workoutexercise
}

type workout struct {
    gorm.model
    name      string    `gorm:"not null" json:"name"`
    createdat time.time `gorm:"not null" json:"created_at"`
    exercises []workoutexercise
}

type workoutexercise struct {
    gorm.model
    workoutid  uint
    workout    workout `gorm:"foreignkey:workoutid;references:id"`
    exerciseid uint
    exercise   exercise `gorm:"foreignkey:exerciseid;references:id"`
    sets       uint
    reps       uint
    weights    uint
}

它产生以下模式(我相信这是所需要的):

gym=# \dt
               list of relations
 schema |       name        | type  |   owner   
--------+-------------------+-------+-----------
 public | installations     | table | gym
 public | workout_exercises | table | gym
 public | workouts          | table | gym
(3 rows)

gym=# \d workouts
                                       table "public.workouts"
   column   |           type           | collation | nullable |               default                
------------+--------------------------+-----------+----------+--------------------------------------
 id         | bigint                   |           | not null | nextval('workouts_id_seq'::regclass)
 created_at | timestamp with time zone |           | not null | 
 updated_at | timestamp with time zone |           |          | 
 deleted_at | timestamp with time zone |           |          | 
 name       | text                     |           | not null | 
indexes:
    "workouts_pkey" primary key, btree (id)
    "idx_workouts_deleted_at" btree (deleted_at)
referenced by:
    table "workout_exercises" constraint "fk_workouts_exercises" foreign key (workout_id) references workouts(id)

gym=# \d exercises
                                       table "public.exercises"
   column    |           type           | collation | nullable |                default                
-------------+--------------------------+-----------+----------+---------------------------------------
 id          | bigint                   |           | not null | nextval('exercises_id_seq'::regclass)
 created_at  | timestamp with time zone |           |          | 
 updated_at  | timestamp with time zone |           |          | 
 deleted_at  | timestamp with time zone |           |          | 
 name        | text                     |           | not null | 
 description | text                     |           | not null | 
indexes:
    "exercises_pkey" primary key, btree (id)
    "idx_exercises_deleted_at" btree (deleted_at)
referenced by:
    table "workout_exercises" constraint "fk_exercises_workouts" foreign key (exercise_id) references exercises(id)

gym=# \d workout_exercises
                                       table "public.workout_exercises"
   column    |           type           | collation | nullable |                    default                    
-------------+--------------------------+-----------+----------+-----------------------------------------------
 id          | bigint                   |           | not null | nextval('workout_exercises_id_seq'::regclass)
 created_at  | timestamp with time zone |           |          | 
 updated_at  | timestamp with time zone |           |          | 
 deleted_at  | timestamp with time zone |           |          | 
 workout_id  | bigint                   |           |          | 
 exercise_id | bigint                   |           |          | 
 sets        | bigint                   |           |          | 
 reps        | bigint                   |           |          | 
 weights     | bigint                   |           |          | 
indexes:
    "workout_exercises_pkey" primary key, btree (id)
    "idx_workout_exercises_deleted_at" btree (deleted_at)
foreign-key constraints:
    "fk_exercises_workouts" foreign key (exercise_id) references exercises(id)
    "fk_workouts_exercises" foreign key (workout_id) references workouts(id)

如果您考虑一下,在没有附加属性的情况下进行锻炼是没有意义的。如果您只想获取锻炼的练习,您可以从中间模型中提取它*:

workout := Workout
db.Preload("WorkoutExercise.Exercise").First(&workout, 10)

for _, we := range workout.Exercises {
    // access reps, etc directly from we
    // and access the exercise from the property we.Exercise
    log.Printf("do %d sets of %d repetitions of %s", we.Sets, we.Reps, 
               we.Exercise.Name)
}

*免责声明 - 尚未实际运行此代码(其余部分有效)。请查看 Nested Preloading 以实现一些深度嵌套的预加载。

理论要掌握,实操不能落!以上关于《Gorm 协会多对多》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

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