首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Gorm关联多对多

Gorm关联多对多
EN

Stack Overflow用户
提问于 2020-07-27 05:02:36
回答 2查看 975关注 0票数 2

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

下面是我的例子

我有两个gorm模型

代码语言:javascript
复制
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多对多关联,它将创建一个workout_exercise连接表,但我如何确保填充其他字段,如reps和sets。这是需要在控制器中完成的事情,而不是gorm处理的事情。我用Nodejs和sequelize做过类似的事情,但对go和gorm世界来说真的很陌生。

EN

回答 2

Stack Overflow用户

发布于 2021-11-24 09:58:29

参加派对有点晚了但是..。我的目标是创造类似的东西,在花了一整天的时间,然后撞到了一堵墙,退了一步重新思考……

经过深思熟虑后,许多游戏,以及一个朋友的好建议,决定从一个稍微不同的角度来处理。

如果你以不同的方式看待它,你可以将它“重新表述”为两个有-一个(或属于-to)和两个一对多:

锻炼锻炼有很多锻炼和锻炼,workout-exercise

  • workout-exercise有很多关于锻炼和一次锻炼的经验

此外,在我的游戏中,我意识到多对多表的属性(列)在上面的模型中没有被引用,所以它无论如何都没有用。

如果你把锻炼看作一个“一流”的模型,它开始变得更有意义,变得更有用:

锻炼你可以创建练习-这是一种静态的锻炼池可以创建锻炼,然后你可以使用resources

  • You -

  • 模型将锻炼填充到锻炼中。

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

代码语言:javascript
复制
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
}

它的结果是以下模式(我认为这是所需的):

代码语言:javascript
复制
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)

如果你想一想,在没有额外属性的情况下拉出锻炼的练习是没有意义的。如果你只想获得锻炼的练习,你可以从中介模型中提取*

代码语言:javascript
复制
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,以实现一些深度嵌套的急切加载。

票数 0
EN

Stack Overflow用户

发布于 2020-07-31 14:44:53

代码语言:javascript
复制
type Exercise struct {
    gorm.Model
    Name        string `gorm:"not null" json:"name"`
    Description string `gorm:"not null json:"description"`
    Workouts []Workout `gorm:"many2many:exercise_workout;"`
}
type Workout struct {
    gorm.Model
    Name string `gorm:"not null" json:"name"`
    CreatedAt time.Time `gorm:"not null" json:"created_at"`
}

Many2any的标记值是您定义的关联表名的名称。并使用以下代码加载包含锻炼数据的练习。

代码语言:javascript
复制
var exercises []Exercise
db.Preload("Workouts").Find(&exercises) 

如果您想用锻炼数据加载锻炼,只需在锻炼结构中添加many2many associate,例如:

代码语言:javascript
复制
type Exercise struct {
    gorm.Model
    Name        string `gorm:"not null" json:"name"`
    Description string `gorm:"not null json:"description"`
    Workouts []Workout `gorm:"many2many:exercise_workout;"`
}
type Workout struct {
    gorm.Model
    Name string `gorm:"not null" json:"name"`
    CreatedAt time.Time `gorm:"not null" json:"created_at"`
    Exercises []Exercise `gorm:"many2many:exercise_workout;"`
}

var workouts []Workout
db.Preload("Exercises").Find(&workouts) 
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63105661

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档