【问题标题】:Why does GORM create a custom id when I specify primary key manually?当我手动指定主键时,为什么 GORM 会创建自定义 id?
【发布时间】: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 类型中明确定义它们。

标签: go go-gorm


【解决方案1】:

正如@mkopriva 在 cmets 中所说,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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-08-29
    • 2018-12-30
    • 1970-01-01
    • 2013-08-30
    • 2012-04-16
    • 2022-01-24
    • 2021-08-19
    相关资源
    最近更新 更多