使用GORM

时间:2018-02-21 05:56:17

标签: mysql go go-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)

4 个答案:

答案 0 :(得分:3)

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

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

这是获取列的唯一方法。希望这会有所帮助。

答案 1 :(得分:2)

您可以将OutTime设置为指针,使其可以为null。如doc中所示:

type YourStruct struct {
     OutTime *time.Time
}

然后运行您的查询

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

答案 2 :(得分:0)

只需在查询中指定IS NULL,而无需使用通配符。

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

答案 3 :(得分:0)

正确的代码是:

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