Gorm关联多对多

tjvv9vkg  于 2023-02-17  发布在  Go
关注(0)|答案(3)|浏览(212)

我知道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世界来说真的是新事物。

50pmv0ei

50pmv0ei1#

有点晚了党,但...我的目标是创造一些类似的,并花了一整天的时间后,它,并撞上了墙,退一步重新思考它...
经过一番沉思,许多游戏,和一个朋友的好建议,决定从一个稍微不同的Angular 来处理。
如果你换个Angular 来看,你可以把它“改写”成两个有一个(或属于一个)和两个一对多:

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

此外,在我的游戏中,我意识到多对多表的属性(列)在上面的模型中没有引用,所以它没有任何用处。
如果你把锻炼-锻炼看作是一种“一流”的模式,它开始变得更有意义,更有用:

  • 你可以创建练习--这是一种静态的资源池
  • 您可以创建训练
  • 然后,您可以使用“健身-锻炼”模式将锻炼填充到健身中。

总而言之,我的建议是:

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)
}
  • 免责声明-实际上没有运行过这段代码(其余的都可以)。请查看嵌套预加载来实现一些深度嵌套的急切加载。
toe95027

toe950272#

我想如果你想在连接表中添加一个字段,你可以阅读关于自定义连接表的gorm文档
定义练习结构

type Exercise struct {
    ID          int    `gorm:"primaryKey;"`
    Name        string `gorm:"not null;"`
    Description string `gorm:"not null;"`
}

定义锻炼结构

type Workout struct {
    ID          int    `gorm:"primaryKey;"`
    Name        string `gorm:"not null;"`
    CreatedAt   time.Time `gorm:"not null;"`
}

定义健身锻炼结构

type Workout struct {
    ID          int    `gorm:"primaryKey;"`
    ExerciseID  int
    WorkoutID   int

    Sets        int
    Reps        int
    Weights     int
}

自动迁移前设置连接

db.SetupJoinTable(&Exercise{}, "Workouts", &WorkoutExercise{})

运行自动迁移

db.AutoMigrate(
    &Exercise{},
    &Workout{},
)
olmpazwi

olmpazwi3#

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"`
}

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

var exercises []Exercise
db.Preload("Workouts").Find(&exercises)

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

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)

相关问题