I am making a Go project with gorm for mysql.
When creating a mysql table using gorm, it is necessary to create multiple foreign keys for one table. Until now, it was created like the following code
such a 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"`
}
I had a foreign key like this
MgtDB.AutoMigrate(&Members{}).AddForeignKey("myself_user_id", "users(user_id)", "RESTRICT", "RESTRICT").AddForeignKey("member_user_id", "users(user_id)", "RESTRICT", "RESTRICT")
I feel a little verbose Please let me know if there are other ways like this
Thanks
type Members struct {
...
MemberUserID int32
MemberUser User `gorm:"foreignkey:MemberUserID"`
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.