手动指定主键时,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)