dongwen7730 2017-08-01 15:22
浏览 159
已采纳

go-gorm,postgres:简单插入会返回错误

I'm trying to do simple inserts, trying to evaluate the usefulness of Postgres because of this recent hype. I'm a mongoDB guy. And this is what I'm trying to do:

db, e := gorm.Open("postgres", fmt.Sprintf("host=%s user=%s dbname=%s password=%s sslmode=disable", pgHost, pgUser, pgDatabase, pgPass))
if e != nil {
    log.Fatal(e.Error())
}
defer db.Close()
db.AutoMigrate(&model.Customer{}, &model.Email{}, &model.Address{}, &model.Name{}, &model.Logindata{})

name := new(model.Name)
email := new(model.Email)
customer := &model.Customer{
    Name:         name,
    PrimaryEmail: email,
}
customer.Name.First = "Darko"
customer.Name.Last = "Luketic"
customer.Name.Middle = "" // also tried without this line
customer.PrimaryEmail.Address = "my@mail.come"
customer.PrimaryEmail.Verified = true
tx := db.Begin()

if e := tx.Create(name); e != nil {
    tx.Rollback()
    log.Fatal("create name", e.Error)
}

if e := tx.Create(email); e != nil {
    tx.Rollback()
    log.Fatal("create email", e.Error)
}

if e := tx.Create(customer); e != nil {
    tx.Rollback()
    log.Fatal("create customer", e.Error)
}

tx.Commit()

with the models being

package model

import "github.com/jinzhu/gorm"

type Customer struct {
    gorm.Model
    Name            *Name
    BillingAddress  *Address
    ShippingAddress *Address
    PrimaryEmail    *Email
    AlternateEmails []*Email
    Logindata       *Logindata
}

type Name struct {
    gorm.Model
    First  string `json:"first"`
    Middle string `json:"middle"`
    Last   string `json:"last"`
}

type Logindata struct {
    gorm.Model
    Username string
    Password []byte
}

type Email struct {
    gorm.Model
    Address  string
    Verified bool
}

type Address struct {
    gorm.Model
    Address1 string
    Address2 string
    City     string
    Code     string
    Country  string
}

The output:

go run main.go migrate
migrate called
2017/08/01 17:10:26 create name<nil>
exit status 1

What am I doing wrong? Why is there no error message? How do I fix it?

  • 写回答

2条回答 默认 最新

  • doudi2520 2017-08-01 15:36
    关注

    According to the docs, Create returns a *DB, not an error. So your code should be more like

    if tx = tx.Create(name); tx.Error != nil { /* ... */ }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 给我一个openharmony跑通webrtc实现视频会议的简单demo项目,sdk为12
  • ¥15 vb6.0使用jmail接收smtp邮件并另存附件到D盘
  • ¥30 vb net 使用 sendMessage 如何输入鼠标坐标
  • ¥15 关于freesurfer使用freeview可视化的问题
  • ¥100 谁能在荣耀自带系统MagicOS版本下,隐藏手机桌面图标?
  • ¥15 求SC-LIWC词典!
  • ¥20 有关esp8266连接阿里云
  • ¥15 C# 调用Bartender打印机打印
  • ¥15 我这个代码哪里有问题 acm 平台上显示错误 90%,我自己运行好像没什么问题
  • ¥50 C#编程中使用printDocument类实现文字排版打印问题