jnelson
jnelson

Reputation: 1225

Referencing GORM auto-generated fields in Go

I'm writing my first API, so bear with me. I am using Go, Postgres and GORM and a slew of other things I'm still picking up but I ran into an issue with GORM's AutoMigrate.

Initially my User struct looked like this:

type User struct {
    gorm.Model
    Email    string `gorm:"unique" json:"email"`
    Password string `json:"password"`
}

And when I ran db.AutoMigrate(&User{}) It auto-generated an id field in my User table (along with several date fields), which I wanted. What I am hung up on is figuring out how to reference these fields in my app. I have modified my User struct to now look like this:

type User struct {
    gorm.Model
    ID       int    `gorm:"primary_key" json:"id"`
    Email    string `gorm:"unique" json:"email"`
    Password string `json:"password"`
}

But instead of linking the two id fields, when I access the stored user object as shown:

user := model.User{}
if err := db.First(&user, model.User{Email: email}).Error; err != nil {
    respondError(w, http.StatusNotFound, err.Error())
    return nil
}

there are now two distinct fields, the auto-generated and my own:

{
"ID": 2,
"CreatedAt": "2018-04-28T21:14:20.828547-04:00",
"UpdatedAt": "2018-04-28T21:14:20.828547-04:00",
"DeletedAt": null,
"id": 0,
"email": "[email protected]",
"password": <hash>
}

I realize the answer is likely right in front of my face, there must be a way to reference these auto-generated fields, right?

Upvotes: 0

Views: 2343

Answers (1)

Alireza Bashiri
Alireza Bashiri

Reputation: 452

gorm.Model is a struct including some basic fields, which including fields ID, CreatedAt, UpdatedAt, DeletedAt.

Reference: http://gorm.io/docs/conventions.html#gorm-Model

Upvotes: 3

Related Questions