是否可以在3个模型之间使用多对多? (GORM)

问题描述 投票:0回答:1

是否可以在3个模型之间使用多对多?

我有 3 个模型想要加入桥接表“client_operator_role”

  1. 操作员
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"`
}
  1. 客户
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
}
  1. 角色
type GoadminRole struct {
    ID        uint `gorm:"primaryKey"`
    Name      string
    Slug      string
    CreatedAt time.Time
    UpdatedAt time.Time
    Operators []*Operator `gorm:"many2many:client_operator_role;"`
}

Gorm 文档声明 Many2many 仅适用于 2 个模型。有没有解决方法可以将这三个加入?

go orm go-gorm
1个回答
0
投票

您可以为此使用自定义联接表。 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{})
© www.soinside.com 2019 - 2024. All rights reserved.