9
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

GORMでのUpdateされない場合の注意

Posted at

GORMを使っててちょっとハマったのでメモ。  
結論は公式ドキュメント見ろってことでしたが。

やりたいこと

GORM使ってDBのレコードをアップデート。

ハマったこと

構造体を使って更新すると、各型の初期値(string : "", int: 0など)はGORMに空と見なされるので反映されない。
構造体を使わないで更新すれば良い。

// 反映されない
db.Model(&foo{}).Where("id = ?", hoge).Update(&foo{num: 0})

// 反映される
db.Model(&foo{}).Where("id = ?", hoge).Update("num", 0)

参考

// WARNING when update with struct, GORM will only update those fields that with non blank value
// For below Update, nothing will be updated as "", 0, false are blank values of their types

9
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?