0
0

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 1 year has passed since last update.

GORMのUpdateで構造体を使う場合「文字:""、数値:0、ブール:false」のフィールドが更新されない。

Posted at

既出だったのですが、情報が古かったので記事にしました。

ハマりポイント

構造体で更新する場合、以下のフィールドが更新されない。

  • 文字列:""
  • 数値:0
  • ブール値:false

■更新されない例
以下は「Name, Age, Active」全て更新されない。

db.Model(&user).Updates(User{Name: "", Age: 0, Active: false})

どうすればいいか

2パターンあるようです。

  1. mapを使用して更新する:map[string]interface{}{"name": "hello", "age": 18, "active": false}

    // Select with Map
    db.Model(&user).Updates(map[string]interface{}{"name": "", "age": 0, "active": false})
    
  2. Select を使用して更新する:Select("Name", "Age", "Active")

    // Select with Struct (select zero value fields)
    db.Model(&user).Select("Name", "Age", "Active").Updates(User{Name: "", Age: 0, Active: false})
    

LINK

Link: Extra-Updating-option

NOTE When update with struct, GORM will only update non-zero fields,
you might want to use map to update attributes or use Select to specify fields to update

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?