kozyr
kozyr

Reputation: 1254

go-pg - reading the ID returned after the upsert

I've created an upsert like this in go-pg:

db.Model(myModel).Returning("id").
OnConflict("(fieldA) DO UPDATE set fieldB=EXCLUDED.fieldB").Insert()

and now I'd like to read the returned id. How would I do that? All the examples I've seen ignore the result returned by the insert/update queries.

Upvotes: 5

Views: 3570

Answers (1)

Schwern
Schwern

Reputation: 164919

Judging from the example, the ID will be in myModel.

myModel := &MyModel{
    FieldA: `Something something something`
}

_, err := db.Model(myModel).
    OnConflict("(fieldA) DO UPDATE").
    Set("fieldB = EXCLUDED.fieldB").
    Insert()
if err != nil {
    panic(err)
}

fmt.Println(myModel.Id)

Looking at the Postgres log, it is doing insert into ... returning "id" to get the ID.

Upvotes: 5

Related Questions