Gorm: How to get id of inserted values

Created on 28 Jul 2018  路  7Comments  路  Source: go-gorm/gorm

What version of Go are you using (go version)?

go version go1.10.3 linux/amd64

Which database and its version are you using?

Last version of gorm and postgresql

Please provide a complete runnable program to reproduce your issue.

type AttachmentsNew struct { gorm.Model id intgorm:"AUTO_INCREMENT" ownerId int hashkey stringgorm:"size:64" time int fileInfo string filepath string doctype stringgorm:"size:15"`
}

Database.Create(&AttachmentsNew{ownerId: ownerId, hashkey: "test", time:0, fileInfo:file.oldname, filepath:file.path, doctype:file.documentType})`

How i can get id of inserted value?

Most helpful comment

row := new(Article)
d := Gorm.Create(article).Scan(&row)
if d.Error != nil {
return 0, d.Error
}
return row.Id, nil

All 7 comments

row := new(Article)
d := Gorm.Create(article).Scan(&row)
if d.Error != nil {
return 0, d.Error
}
return row.Id, nil

My ID is autoincrement.

Your code return ID - 0, buy ID is 6;

Gorm automatically inserts the ID into the struct.

a := &AttachmentsNew{ownerId: ownerId, hashkey: "test", time:0, fileInfo:file.oldname, filepath:file.path, doctype:file.documentType}
Database.Create(a)
// a.id should be populated

Populated means extended?

@DuckerMan yes it means "filled".

So, why i should create variable that point to my structure?

so you can get use the ID after the creation. Otherwise I don't know any other method to achieve this.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

alanyuen picture alanyuen  路  3Comments

Quentin-M picture Quentin-M  路  3Comments

superwf picture superwf  路  3Comments

bramp picture bramp  路  3Comments

zeropool picture zeropool  路  3Comments