Gorm query problem

package main

import (
    "database/sql/driver"
    "fmt"
    "time"
)

type JSONTime struct {
    time.Time
}

// MarshalJSON on JSONTime format Time field with %Y-%m-%d %H:%M:%S
func (t JSONTime) MarshalJSON() ([]byte, error) {
    formatted := fmt.Sprintf("\"%s\"", t.Format("2006-01-02 15:04:05"))
    return []byte(formatted), nil
}

// Value insert timestamp into mysql need this function.
func (t JSONTime) Value() (driver.Value, error) {
    var zeroTime time.Time
    if t.Time.UnixNano() == zeroTime.UnixNano() {
        return nil, nil
    }
    return t.Time, nil
}

// Scan valueof time.Time
func (t *JSONTime) Scan(v interface{}) error {
    value, ok := v.(time.Time)
    if ok {
        *t = JSONTime{Time: value}
        return nil
    }
    return fmt.Errorf("can not convert %v to timestamp", v)
}

type TimeTest struct {
    Id            int64 `gorm:"primary_key"`
    CreatedAt     JSONTime
}

gorm Time.Time type changed to JSONTime. This output via JSON will be converted to a format like 2006-01-02 15:04:05. So how do I assign a value to this CreatedAt now? Or how to convert to JSONTime type through string or time type

start, _ := strconv.Atoi(c.DefaultPostForm("start", time.Now().Format("2006-01-02") + " 05:00:00"))
Db.Model(&User).Where("time >= ?",start)

the above start is automatically converted to 0 in sql. How to deal with this?

Jan.08,2022

  • you define the structure of anonymous variables, adding a definition function
  

I really don't understand why you want JsonTime, time.Time?
this start parameter itself requires the outermost layer to go to a null value for Filter.
and in gorm, created_at and update_at do not need to be manually assigned.

  • How does gorm create data for json fields?

    how does gorm create data for json fields? the official document has an example of creating a record: http: gorm.io zh_CN docs ind. db.Create(&Product{Code: "L1212", Price: 1000}) question: if this Product model has a specifi...

    Dec.20,2021
  • Gorm one-to-many mapping problem

    I use golang s gorm to construct a data model. One posts, one users, one user corresponds to multiple articles posts.go . finally this problem arises, how to solve it ...

    Feb.15,2022
Menu