Gorm没有提供正确的插入记录的主键ID。

huangapple go评论80阅读模式
英文:

Gorm not giving correct inserted record's primary key ID

问题

我正在使用GO的GORM。

我有一个实体User:

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

我的创建记录代码是:

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

根据文档,user.ID应该返回插入数据的主键,但它返回的是0,这是在初始化User结构时的默认值。

英文:

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.

答案1

得分: 1

User.Id将具有正确的值,因为您已经添加了该字段并将其标记为主键。user.ID实际上访问的是user.Model.ID。这也有primaryKey标签,但被您在User类型上的Id字段所取代。

您嵌入了gorm.Model类型(根据文档,我想象的是这样),但这意味着您的User类型实际上是这样的:

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

因此,当您查看user.ID时,您正在访问嵌入的ID字段。要么检查Id字段(小写的d),要么删除您添加的Id字段,并依赖于嵌入的Model中的ID

如果您确实想保留自己的Id字段,我认为gorm.Model将其设置为uint是正确的。如果您需要在数据中处理负ID元素,那么您可能做错了什么...我见过使用负ID的情况,但每次看到这种情况时,都是一些非常糟糕的黑客行为。

英文:

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.

huangapple
  • 本文由 发表于 2021年9月1日 00:47:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/69002525.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定