Gorm 协会多对多

Ale*_*rio 3 database go go-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"`
}

Run Code Online (Sandbox Code Playgroud)

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

Tom*_*gan 8

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

经过一番深思熟虑,玩了很多游戏,再加上朋友的良好建议,我决定从一个稍微不同的角度开始。

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

  • 运动有多种锻炼方式
  • 锻炼有很多锻炼运动
  • 锻炼-锻炼有锻炼和一项锻炼

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

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

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

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

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
}
Run Code Online (Sandbox Code Playgroud)

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

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)
Run Code Online (Sandbox Code Playgroud)

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

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)
}

Run Code Online (Sandbox Code Playgroud)

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