Search code examples
gogo-gormgo-gin

Gorm not giving correct inserted record's primary key ID


I am using GORM with GO.

I have an entity User

type User struct {
    Id int `json:"id" gorm:"primaryKey;autoIncrement"`
    Name string `json:"name"`
    gorm.Model
}

My Create record code is

user := User{}
user.Name = "Afzal"
DB.Create(&user)

Now as per Doc user.ID should return inserted data's primary key

But it's returning 0 which is the default value when struct User was initialized.


Solution

  • User.Id will have the correct value, because you've added that field and tagged it as being the primary key. user.ID actually accesses user.Model.ID. This, too, has the primaryKey tag, but it's superseded by the Id field on your User type.

    You've embedded the gorm.Model type (as per the docs, I imagine), but that means your User type actually looks like this:

    User{
        Id    int
        Name  string
        gorm.Model{
            ID        uint `gorm:"primarykey"`
            CreatedAt time.Time
            UpdatedAt time.Time
            DeletedAt DeletedAt `gorm:"index"`
        }
    }
    

    So when you look at user.ID, you're accessing the embedded ID field. Either check the Id field (lower-case d), or remove the Id field you've added, and rely on the ID from the embedded Model.

    If you do want to keep your own Id field, I think the gorm.Model is right to make it a uint. If you're needing to faff around with negative ID elements in your data, you're probably doing something wrong... I've seen negative ID's being used, but every time I saw it happen, it was some absolutely horrible hack.