【发布时间】:2018-10-26 18:10:07
【问题描述】:
我有这两个模型:
用户模型:
type User struct {
DBBase
Email string `gorm:"column:email" json:"email"`
Password string `gorm:"column:password" json:"-"`
}
func (User) TableName() string {
return "t_user"
}
用户信息模型:
type UserInfo struct {
User User `gorm:"foreignkey:u_id;association_foreignkey:id"`
UID uint `gorm:"column:u_id" json:"-"`
FirstName string `gorm:"column:first_name" json:"first_name"`
LastName string `gorm:"column:last_name" json:"last_name"`
Phone string `gorm:"column:phone" json:"phone"`
Address string `gorm:"column:address" json:"address"`
}
func (UserInfo) TableName() string {
return "t_user_info"
}
我想让 UID 与用户表的 id 相关。
这是创建用户的函数:
func (dao *AuthDAO) Register(rs app.RequestScope, user *models.User, userInfo *models.UserInfo) (userErr error, userInfoErr error) {
createUser := rs.Db().Create(&user)
userInfo.UID = user.ID
createUserInfo := rs.Db().Create(&userInfo)
return createUser.Error, createUserInfo.Error
}
我确实尝试了 gorm 在文档中写的内容,但没有成功: http://doc.gorm.io/associations.html
【问题讨论】:
-
你尝试了什么?
-
@Devon “属于”部分
-
是的......那部分是什么?您没有在上述代码中包含任何关系。
-
@Devon,对不起,你说得对。我编辑了代码。谢谢。
-
外键应该是UID,如果是id则不需要关联外键。