如何为gorm组织多个外键

How to organize multiple foreign keys for gorm

我正在为 mysql.

使用 gorm 做一个 Go 项目

使用gorm创建mysqltable时,需要为一个table创建多个外键。到目前为止,它是像下面的代码创建的

这样的table

type Members struct {
    ID           int32     `gorm:"AUTO_INCREMENT" json:"id" from:"id"`
    MyselfUserID int32     `gorm:"NOT NULL" json:"myself_user_id" from:"myself_user_id"` 
    MemberUserID int32     `gorm:"NOT NULL" json:"member_user_id" from:"family_user_id"` 
    FirstName    string    `json:"first_name" from:"first_name"`
    LastName     string    `json:"last_name" from:"last_name"`
    Relationship string    `json:"relationship" from:"relationship"`
    Image        string    `json:"image" from:"image"`                       
    Version      int32     `gorm:"column:version" json:"version" form:"version"`        
    UpdatedAt    time.Time `gorm:"column:updated_at" json:"updated_at" form:"updated_at"`
    CreatedAt    time.Time `gorm:"column:created_at" json:"created_at" form:"created_at"` 
}

我有一个这样的外键

MgtDB.AutoMigrate(&Members{}).AddForeignKey("myself_user_id", "users(user_id)", "RESTRICT", "RESTRICT").AddForeignKey("member_user_id", "users(user_id)", "RESTRICT", "RESTRICT")

我觉得有点冗长 如果还有其他类似的方法,请告诉我

谢谢

type Members struct {
    ...
    MemberUserID int32
    MemberUser   User   `gorm:"foreignkey:MemberUserID"`
}

document: define a foreign key