go-pg,UpdateNotZero 没有设计更新可为空的字段,怎么办?
go-pg, UpdateNotZero does not update nullable fields by design, how to do?
我很难理解如何使用 go-pg 和 UpdateNotZero()
使模型字段无效。
示例:
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 代码中,我需要 "remove" 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
。
怎么办?
我认为的相关问题:
UpdateNotZero() 只更新有值的字段。设置 player.AccountID = nil 意味着你 player.AccountID 没有价值。我最接近的猜测是 go-pg 将 nil 解析为 null,因此它根本不会更新,因为它 go-pg 认为该字段为空。
将更新限制为仅您尝试更改的字段:
_, err := db.Model(player).WherePK().Set("account_id = NULL").Update()
我很难理解如何使用 go-pg 和 UpdateNotZero()
使模型字段无效。
示例:
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 代码中,我需要 "remove" 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
。
怎么办?
我认为的相关问题:
UpdateNotZero() 只更新有值的字段。设置 player.AccountID = nil 意味着你 player.AccountID 没有价值。我最接近的猜测是 go-pg 将 nil 解析为 null,因此它根本不会更新,因为它 go-pg 认为该字段为空。
将更新限制为仅您尝试更改的字段:
_, err := db.Model(player).WherePK().Set("account_id = NULL").Update()