在GORM中按日期进行过滤

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

Filtering by date in GORM

问题

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

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

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

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

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

  1. type Model struct {
  2. ID uint `gorm:"primary_key"`
  3. CreatedAt time.Time
  4. UpdatedAt time.Time
  5. DeletedAt *time.Time
  6. }
  7. type User struct {
  8. gorm.Model
  9. Username string `sql:"size:32; not null; unique"`
  10. Password string `sql:"not null"`
  11. Locale string `sql:"not null"`
  12. }
英文:

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.

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

and

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

My database model is defined by the following structs:

  1. type Model struct {
  2. ID uint `gorm:&quot;primary_key&quot;`
  3. CreatedAt time.Time
  4. UpdatedAt time.Time
  5. DeletedAt *time.Time
  6. }
  7. type User struct {
  8. gorm.Model
  9. Username string `sql:&quot;size:32; not null; unique&quot;`
  10. Password string `sql:&quot;not null&quot;`
  11. Locale string `sql:&quot;not null&quot;`
  12. }

答案1

得分: 3

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

  1. select * from XXX where deleted_at = NULL

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

  1. select * from XXX where deleted_at is null

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

  1. 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:

  1. select * from XXX where deleted_at = NULL

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

  1. 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):

  1. 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:

确定