在GORM中按日期过滤 [英] Filtering by date in GORM
问题描述
我正在使用 GORM 访问我数据库中的记录.现在,我要检索所有未删除的记录,这意味着属性DeletedAt必须为NULL.
I'm using GORM to access the records in my database. Now I want to retrieve all records that are not deleted which means, that the attribute DeletedAt must be NULL.
我使用 WHERE()
尝试了以下命令链,但未返回任何结果.
I tried the following command chains with WHERE()
, but they returned no results.
users := []*models.User{}
db.Where("deleted_at", nil).Find(&users)
和
db.Where("deleted_at", "NULL").Find(&users)
我的数据库模型由以下结构定义:
My database model is defined by the following structs:
type Model struct {
ID uint `gorm:"primary_key"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt *time.Time
}
type User struct {
gorm.Model
Username string `sql:"size:32; not null; unique"`
Password string `sql:"not null"`
Locale string `sql:"not null"`
}
推荐答案
对于所有RDBMS,SQL标准都要求涉及与NULL值进行比较的条件始终为false.因此,以下查询始终返回空结果:
With all RDBMS, the SQL standard mandates that a condition involving a comparison with a NULL value is always false. The following query therefore always returns an empty result:
select * from XXX where deleted_at = NULL
如果要搜索NULL值,则应编写:
If you want to search for NULL values, you are supposed to write:
select * from XXX where deleted_at is null
我认为您可以通过确保GORM生成正确的查询来解决此问题.例如,这应该可以工作(未经测试):
I think you can fix the issue by making sure GORM generates the correct query. For instance, this should work (untested):
db.Where("deleted_at is null").Find(&users)
这篇关于在GORM中按日期过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!