[英]go-pg, UpdateNotZero does not update nullable fields by design, how to do?
我很難理解如何使用go-pg和UpdateNotZero()
使 model 字段無效。
例子:
type Player struct {
ID int
CreatedAt time.Time `pg:"default:now(),notnull"`
UpdatedAt time.Time
AccountID *int
}
假設我現在有這個播放器:
+----+------------+------------+------------+
| ID | created_at | updated_at | account_id |
+----+------------+------------+------------+
| 1 | 2020-06-16 | NULL | 12 |
+----+------------+------------+------------+
在我的 GO 代碼中,我需要“刪除” AccountID
,我需要取消它:從12
到NULL
。
如果我像這樣使用update()
:
...
player.AccountID = nil
_, err := db.Model(player).WherePK().Update()
它給了我錯誤:
ERROR #23502 null value in column \"created_at\" violates not-null constraint"
如果我像這樣使用UpdateNotZero()
:
...
player.AccountID = nil
_, err := db.Model(player).WherePK().UpdateNotZero()
它根本不更新AccountID
。
怎么做?
我認為的相關問題:
將更新限制為僅您嘗試更改的字段:
_, err := db.Model(player).WherePK().Set("account_id = NULL").Update()
UpdateNotZero() 僅更新具有值的字段。 設置 player.AccountID = nil 意味着你的 player.AccountID 沒有價值。 我最接近的猜測是 go-pg 將 nil 解析為 null,因此它根本不會更新,因為它 go-pg 認為該字段為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.