Filtering by date in GORM

。_饼干妹妹 提交于 2019-12-13 00:13:16

问题


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.

I tried the following command chains with WHERE(), but they returned no results.

users := []*models.User{}
db.Where("deleted_at", nil).Find(&users)

and

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"`
}

回答1:


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

If you want to search for NULL values, you are supposed to write:

select * from XXX where deleted_at is null

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)


来源:https://stackoverflow.com/questions/30234610/filtering-by-date-in-gorm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!