Gorm: How Do I Set a Field To NULL?

Created on 17 Jun 2016  路  5Comments  路  Source: go-gorm/gorm

I want to undelete some things, is there a proper way to do this?

Most helpful comment

or Update("column", gorm.Expr("NULL")) or use nil for pointer.

All 5 comments

I've found that if you use a nullable struct like mysql.NullTime you can write null into it's field by setting the Time to a non-default value and setting Valid to false.

type Example struct {
    Id                     string
    SomeTime       mysql.NullTime
}
example := Example{ Id: "1", SomeTime: mysql.NullTime{ Time: Time.Now(), Valid: False}
db.Model(&example).Updates(&example)
// This produces UPDATE examples SET some_time = NULL WHERE Id = '1'

This works because gorm ignores fields with default values for update, but by setting the Time field, we force it to write Null.

or Update("column", gorm.Expr("NULL")) or use nil for pointer.

in the case, i have some some fields which i set type String in model, should i use Update("column", gorm.Expr("NULL")) for multi times?
any option to update NULL except use pointer?

@jinzhu , any update for multiple columns and how can we insert multiple fields having NULL values for some fields?

@SantoshSah I have used with success a map[string]interface{} instead of a struct . Having nil as the value of the desired null property

Was this page helpful?
0 / 5 - 0 ratings

Related issues

Quentin-M picture Quentin-M  路  3Comments

easonlin404 picture easonlin404  路  3Comments

kumarsiva07 picture kumarsiva07  路  3Comments

littletwolee picture littletwolee  路  3Comments

bramp picture bramp  路  3Comments