Postgresql 带有json数据的GORM数据库COLUN
我正在尝试编写一个电子邮件服务,在这里我想使用gorm将一些与电子邮件相关的数据存储到Postgres数据库中。我有一个字段需要存储为JSON blob,在请求中作为JSON对象传递。当我尝试迁移时,错误总是说不支持类型映射。当手动添加数据库,然后运行gorm时,它不会将行写入数据库 我见过一些例子,其中它使用Postgresql 带有json数据的GORM数据库COLUN,postgresql,go,go-gorm,Postgresql,Go,Go Gorm,我正在尝试编写一个电子邮件服务,在这里我想使用gorm将一些与电子邮件相关的数据存储到Postgres数据库中。我有一个字段需要存储为JSON blob,在请求中作为JSON对象传递。当我尝试迁移时,错误总是说不支持类型映射。当手动添加数据库,然后运行gorm时,它不会将行写入数据库 我见过一些例子,其中它使用postgres.Json作为字段类型,但我希望从请求中加载的字段作为map[string]字符串 // Email : Base with injected fields `UUID`,
postgres.Json
作为字段类型,但我希望从请求中加载的字段作为map[string]字符串
// Email : Base with injected fields `UUID`, `CreatedAt`, `UpdatedAt`
type Email struct {
gorm.Model
Status string `grom:"type:varchar(32);not null"`
TemplateID string `grom:"type:varchar(256)"`
ToEmai string `grom:"type:varchar(256);not null"`
FromEmail string `grom:"type:varchar(256);not null"`
ToName string `grom:"type:varchar(256);not null"`
FromName string `grom:"type:varchar(256);not null"`
Subject string `grom:"type:varchar(256)"`
Message string `grom:"type:varchar"`
DynamicData *map[string]string `grom:"type:json"`
}
这是我的模型
然后我提出一个请求:
// SendEmail : sends an email
func SendEmail(c *gin.Context) {
body, err := ioutil.ReadAll(c.Request.Body)
if err != nil {
log.Error("Error reading request body to get rate estimates")
}
var newEmail = models.Email{
Status: "PENDING",
}
jsonErr := json.Unmarshal(body, &newEmail)
if jsonErr != nil {
log.Error(jsonErr)
}
database.DB.Create(&newEmail)
defer c.Request.Body.Close()
err = newEmail.SendSendgridEmail()
if err != nil {
c.JSON(http.StatusBadRequest, err)
} else {
c.JSON(http.StatusOK, "Successfully sent email")
}
}
然后研究这个函数
func (e Email) dynamicTemplateEmailBody() []byte {
newMail := mail.NewV3Mail()
emailFrom := mail.NewEmail(e.FromName, e.FromEmail)
newMail.SetFrom(emailFrom)
newMail.SetTemplateID(e.TemplateID)
p := mail.NewPersonalization()
tos := []*mail.Email{
mail.NewEmail(e.ToName, e.ToEmai),
}
p.AddTos(tos...)
if e.DynamicData != nil {
for key, value := range *e.DynamicData {
log.Infof("%s %s", key, value)
p.SetDynamicTemplateData(key, value)
}
}
newMail.AddPersonalizations(p)
return mail.GetRequestBody(newMail)
}
我希望能够运行DB.AutoMigrate(&models.Email{})
并自动迁移对象,或者当我向端点发出请求时,该行被添加到我的电子邮件表中