【发布时间】:2020-08-13 21:18:03
【问题描述】:
我有一个 GORM 模型:
type User struct {
gorm.Model
Name, PhotoId, Bio string
ChatId int64 `gorm:"primary_key;auto_increment:false"`
Gender, Orientation int
}
如您所见,我手动指定了主键。但是当我检查 GORM 创建的表时:
postgres=# \d users
Table "public.users"
Column | Type | Collation | Nullable | Default
-------------+--------------------------+-----------+----------+----------------------------------------
id | integer | | not null | nextval('users_id_seq'::regclass)
created_at | timestamp with time zone | | |
updated_at | timestamp with time zone | | |
deleted_at | timestamp with time zone | | |
name | text | | |
photo_id | text | | |
bio | text | | |
chat_id | bigint | | not null | nextval('users_chat_id_seq'::regclass)
gender | integer | | |
orientation | integer | | |
Indexes:
"users_pkey" PRIMARY KEY, btree (id, chat_id)
"idx_users_deleted_at" btree (deleted_at)
我可以看到 GORM 还添加了 id 列,该列也用作键。为什么会这样?这是否意味着当我做这样的事情时:
var user User
db.First(&user, 1)
Gorm 会使用id=1 而不是chat_id=1 查找用户?
【问题讨论】:
-
因为您使用的是
gorm.Model,它还定义了一个主键字段,即ID uint `gorm:"primary_key"`。如果您想要自定义非复合主键,则必须从User类型中删除嵌入的gorm.Model。 -
@mkopriva 哦,我认为 gorm 有必要在结构中包含它。谢谢!
-
请记住,删除
gorm.Model也会删除 3 个时间戳字段,因此如果您需要这些时间戳中的任何一个,您必须在User类型中明确定义它们。