如何解决手动指定主键时,GORM为什么会创建自定义ID?
我有一个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
查找用户吗?
解决方法
正如@mkopriva在评论中所说,gorm.Model
添加了id列。如果我从结构定义中删除它,则表将按预期创建:
postgres=# \d users
Table "public.users"
Column | Type | Collation | Nullable | Default
-------------+---------+-----------+----------+---------
name | text | | |
photo_id | text | | |
bio | text | | |
chat_id | bigint | | not null |
gender | integer | | |
orientation | integer | | |
Indexes:
"users_pkey" PRIMARY KEY,btree (chat_id)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。