null icon indicating copy to clipboard operation
null copied to clipboard

how use json null set sql time field to null?

Open ystyle opened this issue 3 years ago • 3 comments

  1. defind web api dto struct
type Dto struct {
   Start null.Time
}
  1. send this json to web api
{ 
  "Start": null
}
  1. service: use gorm update entry
gorm.Model(&MyTable).Where("id = 1").Update(&dto)
  1. Hope to generate sql
update my_table set start = null  where id = 1

The start field is now ignored when used in this way

ystyle avatar Dec 09 '22 08:12 ystyle

Sounds like a GORM issue to me. I don't use it and I can't provide support for it. I would suggest that after you unmarshal the JSON input, check whether null.Time is properly set to null or not. If it looks OK, then it's almost certainly a GORM issue.

guregu avatar Dec 10 '22 09:12 guregu

The result is the same whether the time type is passed or not, how to set a zero value for the time image

ystyle avatar Mar 15 '23 06:03 ystyle

I feel a better option would be to use the Golang stdlib data structures for null SQL values. Those will generally be supported by all Golang ORMs, including GORM as their documentation on model declaration specifically uses them (https://gorm.io/docs/models.html).

The relevant type here would be: sql.NullTime (https://pkg.go.dev/database/sql#NullTime)

Unfortunately, you will need to have logic to copy the data from the source type into the destination type. However, you would have incurred that "extra" step no matter what.

oogali avatar Jan 27 '24 16:01 oogali