当我们在 gorm 中创建 many2many 关联时,有没有办法添加自定义列?
Is there a way to add a custom column when we create a many2many association in gorm?
我想知道两件事
我从类似的问题中得到了以下结构。
// models/school.go
type School struct {
ID int `gorm:"primary_key"`
Name string `gorm:"not null"`
Accreditations []Accreditation `gorm:"many2many:school_accreditation;"`
}
type Accreditation struct {
// "accreditation" table
ID int `gorm:"primary_key"`
Name string
Description string
}
因此,默认情况下,这将创建一个包含 2 列的 school_accreditation
table:
- 一个会有学校ID
- 其他人将拥有 认证 ID
我的问题:
- 向
school_accreditation
table 添加另一列的最有效方法是什么?
- 假设我想在
school_accreditation
table.
中包含 Accreditation
的 Name
字段
2.1) 我如何实现这个,例如:school_accreditation
将有 school_id
、accreditation_id
、accreditation_name
对于第一个问题,
这似乎是通过定义 SchoolAccreditation
模型并向其添加字段来实现的唯一方法。
此外,它让我对这段关系有更多的控制权。
对于第二个问题,如果有的话,我还没有找到办法!
博斯特
对于第二个,
您必须从 Accreditation
手动获取 name
,然后通过定义的 SchoolAccreditation
模型将其添加到列中。
我想知道两件事 我从类似的问题中得到了以下结构。
// models/school.go
type School struct {
ID int `gorm:"primary_key"`
Name string `gorm:"not null"`
Accreditations []Accreditation `gorm:"many2many:school_accreditation;"`
}
type Accreditation struct {
// "accreditation" table
ID int `gorm:"primary_key"`
Name string
Description string
}
因此,默认情况下,这将创建一个包含 2 列的 school_accreditation
table:
- 一个会有学校ID
- 其他人将拥有 认证 ID
我的问题:
- 向
school_accreditation
table 添加另一列的最有效方法是什么? - 假设我想在
school_accreditation
table.
中包含Accreditation
的Name
字段 2.1) 我如何实现这个,例如:school_accreditation
将有school_id
、accreditation_id
、accreditation_name
对于第一个问题,
这似乎是通过定义 SchoolAccreditation
模型并向其添加字段来实现的唯一方法。
此外,它让我对这段关系有更多的控制权。
对于第二个问题,如果有的话,我还没有找到办法!
博斯特
对于第二个,
您必须从 Accreditation
手动获取 name
,然后通过定义的 SchoolAccreditation
模型将其添加到列中。