Gorm: db.NewRecord() return false when I insert something first time

Created on 27 May 2016  路  4Comments  路  Source: go-gorm/gorm

type Ip_distribution struct {
    Ip          string `gorm:"primary_key"`
}
type Ip struct {
    Ip     string
}

func (i *Ip_distribution) TableName() string {
    return "ip_distribution"
}

func main() {
    db, _ := gorm.Open("mysql", "abc:123@tcp(10.10.10.10:3306)/ramos?charset=utf8&loc=Local")
    item := Ip_distribution{Ip: "1.1.1.1"} 
    fmt.Println(db.NewRecord(item))
    db.Create(&item)
    fmt.Println(db.NewRecord(item))

The 1.1.1.1 doesn't exist in mysql before run this function. But the result is :

false

You know, it should return true when we execute db.NewRecord(item) first time. Is this a bug or I misused this function?

Most helpful comment

The NewRecord method only check if current value has primary key or not.

If you want to ensure this primary key exists in database, you need to query that like:

db.First(&Ip_distribution{}, "ip = ?", "1.1.1.1").RecordNotFound()

All 4 comments

+1 I have the same problem with object having string as primary_key !

same issue +1

The NewRecord method only check if current value has primary key or not.

If you want to ensure this primary key exists in database, you need to query that like:

db.First(&Ip_distribution{}, "ip = ?", "1.1.1.1").RecordNotFound()

The comment on the method was confusing me too, thank you for clearing that out @jinzhu

Was this page helpful?
0 / 5 - 0 ratings