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

Fetching NULL datetime value in MySQL using GORM

我想使用 Gorm 获取具有 out_time 和 NULL 的最后 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)

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

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

这是一个获取列的方法。希望这有帮助。

您可以将OutTime 设置为一个指针,这样它就可以为空。正如在 doc:

中看到的
type YourStruct struct {
     OutTime *time.Time
}

然后运行你的查询

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

只需在不带通配符的查询中指定 IS NULL

db.Where("out_time IS NULL").Last(&visitDetail)

正确的代码是:

db.Where("out_time is ?", nil).Last(&visitDetail)