小编典典

使用GORM在MySQL中获取NULL日期时间值

go

我想NULL使用Gorm 来获取具有out_time的最后一个visit_details行。 NIL本身就是VisitDetail
OutTime为的类型mysql.NullTime

码:-

var visitDetail models.VisitDetail
db.Where("out_time=? ", nil).Last(&visitDetail)

//model VisitDetails
type VisitDetail struct {
    Id              int
    Visitor         Visitor  `gorm:"foreignkey:ClientId;association_foreignkey:Id"`
    VisitorId       int      `gorm:"not null;"`
    Location        Location `gorm:"foreignkey:LocationId;association_foreignkey:Id"`
    LocationId      int      `gorm:"not null;"`
    Purpose         string
    InTime          time.Time `gorm:"not null;"`
    OutTime         mysql.NullTime
    User            User `gorm:"foreignkey:ClientId;association_foreignkey:Id"`
    UserId          int  `gorm:"not null;"`
    Status          int  `gorm:"not null;"`
    ApproveByClient int  `gorm:"not null;"`
}

查询:

select * from visit_details where out_time is NULL order by id desc limit 1;
+----+------------+-------------+---------+---------------------+----------+---------+--------+-------------------+
| id | visitor_id | location_id | purpose | in_time             | out_time | user_id | status | approve_by_client |
+----+------------+-------------+---------+---------------------+----------+---------+--------+-------------------+
| 20 |          1 |           8 |         | 2018-02-20 17:13:25 | NULL     |    1609 |      0 |                 0 |
+----+------------+-------------+---------+---------------------+----------+---------+--------+-------------------+
1 row in set (0.04 sec)

阅读 1173

收藏
2020-07-02

共1个答案

小编典典

Go不能特别识别NULL。我认为您可以使用GORM中的原始查询来实现。像这样。

db.Raw("SELECT * FROM visit_details WHERE out_time is NULL order by id desc limit 1").Scan(&visitDetail)

这是一个获取专栏的文章。希望这可以帮助。

2020-07-02