英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论