在GORM中按日期进行过滤

huangapple go评论86阅读模式
英文:

Filtering by date in GORM

问题

我正在使用GORM来访问数据库中的记录。现在我想检索所有未被删除的记录,也就是说,DeletedAt属性必须为NULL。

我尝试了以下使用WHERE()的命令链,但它们没有返回结果。

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

db.Where("deleted_at", "NULL").Find(&users)

我的数据库模型由以下结构定义:

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"`
}
英文:

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.

<!-- language: lang-go -->

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

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

and

db.Where(&quot;deleted_at&quot;, &quot;NULL&quot;).Find(&amp;users)

My database model is defined by the following structs:

type Model struct {
    ID        uint `gorm:&quot;primary_key&quot;`
    CreatedAt time.Time
    UpdatedAt time.Time
    DeletedAt *time.Time
}

type User struct {
    gorm.Model
    Username string `sql:&quot;size:32; not null; unique&quot;`
    Password string `sql:&quot;not null&quot;`
    Locale   string `sql:&quot;not null&quot;`
}

答案1

得分: 3

在所有关系型数据库管理系统(RDBMS)中,SQL标准规定与NULL值进行比较的条件始终为false。因此,以下查询始终返回空结果:

select * from XXX where deleted_at = NULL

如果你想搜索NULL值,应该写成:

select * from XXX where deleted_at is null

我认为你可以通过确保GORM生成正确的查询语句来解决这个问题。例如,下面的代码应该可以工作(未经测试):

db.Where("deleted_at is null").Find(&users)
英文:

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(&quot;deleted_at is null&quot;).Find(&amp;users)

huangapple
  • 本文由 发表于 2015年5月14日 18:09:28
  • 转载请务必保留本文链接:https://go.coder-hub.com/30234610.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定