我正在尝试使用此代码将数据写入具有关系的 PostgreSQL 数据库。
req := c.Request()
tx := c.Value("tx").(*pop.Connection)
user := &models.User{}
if req.FormValue("user_type") == "0" {
salt, _ := strconv.Atoi(os.Getenv("SALT"))
userType, _ := strconv.Atoi(req.FormValue("user_type"))
user.UserType = int16(userType)
user.Phone, _ = strconv.ParseInt(req.FormValue("phone"), 10, 64)
hash, _ := bcrypt.GenerateFromPassword([]byte(req.FormValue("password")), salt)
user.PassHash = string(hash)
user.Balance = 0
user.Validated = false
user.Person = &models.Person{
Name: req.FormValue("name"),
City: req.FormValue("city"),
}
} else {
}
err := tx.Eager().Create(user)
fmt.Println(errors.WithStack(err))
return c.Render(200, r.JSON(map[string]string{"message": "User successfully created"}))
用户型号:
type User struct {
ID int64 `db:"id" rw:"w" form:"-"`
UserType int16 `db:"user_type" form:"-"`
Phone int64 `db:"phone"`
PassHash string `db:"pass_hash" form:"-"`
Balance int64 `db:"balance" form:"-"`
Avatar nulls.String `db:"avatar" form:"-"`
Validated bool `db:"validated" form:"-"`
//Company *Company `has_one:"company" fk_id:"user_id"`
Person *Person `has_one:"person" fk_id:"user_id"`
}
人物模型:
type Person struct {
ID int64 `db:"id"`
Name string `db:"name"`
Email nulls.String `db:"email"`
City string `db:"city"`
UserId int64 `db:"user_id"`
User *User `belongs_to:"user"`
}
tx.Eager().Create
只是为用户模型创建一行。未创建 Person 模型的行。尝试打印时,在没有堆栈跟踪的情况下发生以下错误。
could not set '%!s(int64=15)' to '<invalid reflect.Value>'
任何帮助将不胜感激。