我在 postgres 中有一個表,其 UUID 欄位型別必須是唯一的,但可以為空
有這樣的桌子和模型
CREATE TABLE IF NOT EXISTS asdf(
id bigserial primary key,
name varchar(255) NOT NULL,
key uuid unique,
created_at timestamptz,
updated_at timestamptz
);
和 go 模型定義為
type Asdf struct {
ID uint64 `json:"id" gorm:"type:uuid;column:id"`
Name string `json:"name" gorm:"column:name"`
Key uuid.UUID `json:"key" gorm:"column:key"`
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
}
result := db.Connect().Create(asdf.Asdf{ID:123,Name:"This is the name"})
并將以下 sql 查詢列印到終端
INSERT INTO "asdf" ("id","name","key","created_at","updated_at")
VALUES('123','This is the name','00000000-0000-0000-0000-000000000000','2022-04-27 03:41:49.338','2022-04-27 03:41:49.338')
00000000-0000-0000-0000-000000000000它將模型作為key值而不是 NULL插入到資料庫中
我還注意到這種情況發生在字串型別中,它插入了一個空字串''而不是 NULL
我如何讓 gorm 插入 NULL 而不是零/空字串作為值?
uj5u.com熱心網友回復:
嘗試將您的欄位型別更改為指標型別:
type Asdf struct {
ID uint64 `json:"id" gorm:"type:uuid;column:id"`
Name string `json:"name" gorm:"column:name"`
Key *uuid.UUID `json:"key" gorm:"column:key"`
CreatedAt time.Time `json:"created_at" gorm:"column:created_at"`
UpdatedAt time.Time `json:"updated_at" gorm:"column:updated_at"`
}
您顯然也必須調整您的 go 代碼(例如:檢查 if record.Key != nil、 access*record.Key而不是record.Key等...)
我認為 gorm 也尊重常規的 sql 介面,所以你也可以嘗試定義一個實作的自定義型別:
sql.Scanner變成sql -> go 轉換null,""driver.Valuer(從sql/driver包中)打開""-null> sql 轉換。
不過我還沒有測驗過,所以你必須自己嘗試一下。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/466888.html
標籤:PostgreSQL 去 戈戈姆
