我有 3 个模型想要加入桥接表“client_operator_role”
type Operator struct {
gorm.Model
Title string `gorm:"unique;not null" validate:"required,min=1,max=100"`
Email string `gorm:"not null;unique" validate:"required,email"`
Mobile string `gorm:"not null" validate:"required,min=7,max=15,numeric"`
Last_online time.Time `gorm:"default:null" validate:"omitempty"`
Last_ip string `gorm:"default:null" validate:"omitempty,ip"`
Clients []*Client `gorm:"many2many:client_operator_role;"`
Cli_ids []string `gorm:"-:all" validate:"omitempty,dive,numeric"` // placeholder field, wont be part of table
GoadminCustomUser GoadminCustomUser `validate:"omitempty,dive"`
}
type Client struct {
gorm.Model
Name string `gorm:"unique;not null" validate:"required,min=1,max=30"`
Kyc_status string `gorm:"not null" validate:"required,min=1,max=30"`
Kyc_remarks string `gorm:"default:null" validate:"omitempty,min=0,max=200"`
Operators []*Operator `gorm:"many2many:client_operator_role;"`
Op_ids []string `gorm:"-:all" validate:"omitempty,dive,numeric"` // placeholder field, wont be part of table
Users []User
}
type GoadminRole struct {
ID uint `gorm:"primaryKey"`
Name string
Slug string
CreatedAt time.Time
UpdatedAt time.Time
Operators []*Operator `gorm:"many2many:client_operator_role;"`
}
您可以为此使用自定义联接表。 https://gorm.io/docs/many_to_many.html#Customize-JoinTable
创建桥接表
type Connection struct {
gorm.Model
RoleID int `gorm:"primaryKey"`
ClientID int `gorm:"primaryKey"`
OperatorID int `gorm:"primaryKey"`
}
为每个模型添加表格引用
type Operator struct {
// ..
Clients []*Client `gorm:"many2many:connections;"`
Roles []*Role `gorm:"many2many:connections;"`
}
type Client struct {
// ..
Operators []*Operator `gorm:"many2many:connections;"`
Roles []*Role `gorm:"many2many:connections;"`
}
type Role struct {
// ..
Clients []*Client `gorm:"many2many:connections;"`
Operators []*Operator `gorm:"many2many:connections;"`
}
你应该使用
SetupJoinTable
功能。
类似的东西对我有用:
// do not forget to check for errors
db.SetupJoinTable(&models.Operator{}, "Roles", &models.Connection{})
db.SetupJoinTable(&models.Operator{}, "Clients", &models.Connection{})
db.SetupJoinTable(&models.Client{}, "Roles", &models.Connection{})
db.SetupJoinTable(&models.Client{}, "Operators", &models.Connection{})
db.SetupJoinTable(&models.Role{}, "Clients", &models.Connection{})
db.SetupJoinTable(&models.Role{}, "Operators", &models.Connection{})