亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何將 NULL 值插入 UUID 而不是零

如何將 NULL 值插入 UUID 而不是零

Go
波斯汪 2022-12-05 17:21:22
我在 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 而不是零/空字符串作為值?
查看完整描述

2 回答

?
慕慕森

TA貢獻1856條經驗 獲得超17個贊

嘗試將您的字段類型更改為指針類型:


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.Keyinstead ofrecord.Key等等......)


我認為 gorm 也尊重常規的 sql 接口,所以你也可以嘗試定義一個實現的自定義類型:

  • sql.Scanner變成on sql -> go conversions null,""

  • driver.Valuer(從sql/driver包中)轉到""on nullgo -> sql conversions。

不過我還沒有測試過,所以你必須自己嘗試一下。


查看完整回答
反對 回復 2022-12-05
?
白衣非少年

TA貢獻1155條經驗 獲得超0個贊

問題中未指定您使用的包。如果你使用satori/go.uuid,你可以使用NullUUID 類型

type Asdf struct {

    ID          uint64         `json:"id" gorm:"type:uuid;column:id"`

    Name        string         `json:"name" gorm:"column:name"`

    NullableKey uuid.NullUUID `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"`

}

要設置一個值:


key := uuid.NullUUID{

    Value: id,  // of type uuid.UUID

    Valid: true

}

要保存 null,只需保存零值即可。&方法都已定義Scan。Value


查看完整回答
反對 回復 2022-12-05
  • 2 回答
  • 0 關注
  • 138 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號