UserService.go
func (service UserService) Create(model *models.User) (*models.User, error) {
db, err := database.GetConnection()
if err != nil {
return nil, err
}
tx := db.Begin()
if tx.Error != nil {
fmt.Errorf("%v", err)
return nil, err
}
if err := tx.Create(model).Error; err != nil {
fmt.Errorf("%v", err)
tx.Rollback()
return nil, err
}
if err := tx.Save(model).Error; err != nil {
fmt.Errorf("%v", err)
tx.Rollback()
return nil, err
}
if err := service.UserProfileService.Create(tx, model); err != nil {
fmt.Errorf("%v", err)
tx.Rollback()
return nil, err
}
if err := tx.Commit().Error; err != nil {
fmt.Errorf("%v", err)
return nil, err
}
return model, nil
}
UserProfileService.go
func (UserProfileService) Create(tx *gorm.DB, user *models.User) error {
if err := tx.Create(models.UserProfile{User: user}).Error; err != nil {
return err
}
return nil
}
User.go
type User struct {
Id *uuid.UUID `json:"id" gorm:"not null;primary_key;type:uuid;default:uuid_generate_v4();"`
Name *string `json:"name" gorm:"not null;type:varchar(255);"`
CreatedAt time.Time `json:"createdAt" gorm:"type:timestamp;default:now()"`
UpdatedAt time.Time `json:"updatedAt" gorm:"type:timestamp;default:now()"`
DeletedAt *time.Time `json:"deleteAt,omitempty" gorm:"type:timestamp;"`
}
func (User) TableName() string {
return "users"
}
UserProfile.go
type UserProfile struct {
User *User `json:"id" gorm:"not null;primary_key;foreignkey:Id;type:uuid;default:uuid_generate_v4();"`
Id *uuid.UUID `json:"id" gorm:"not null;type:uuid"`
Description string `json:"description" gorm:"not null;type:varchar(255)"`
UpdatedAt time.Time `json:"updatedAt" gorm:"type:timestamp;default:now()"`
}
func (UserProfile) TableName() string {
return "users_profile"
}
因此,每个用户必须只有一个UserProfile,这就是UserProfile的主键也是外键(User(id))的原因。但是当我尝试提出请求时,我收到了这个错误:(using unaddressable value)
有关如何使其发挥作用的任何想法?
答案 0 :(得分:0)
您在UserProfileService.go中插入的模型不是指针,这就是您收到func (UserProfileService) Create(tx *gorm.DB, user *models.User) error {
if err := tx.Create(*models.UserProfile{User: user}).Error; err != nil {
return err
}
return nil
}
错误的原因。
tx.Create
<h:form>
<h:inputText value="#{helloBean.name}"></h:inputText>
<h:commandButton value="Welcome Me" action="#{helloBean.submit}">
<f:param name="country" value="#{param.country}" />
</h:commandButton>
</h:form>
调用中的引用很可能会修复您的错误。如果没有,请发布完整的错误。