dongzhang1987
dongzhang1987
2018-07-04 14:43

如何显式查找字段为NULL的记录?

已采纳

From the documentation:

When query with struct, GORM will only query with those fields has non-zero value, that means if your field’s value is 0, '', false or other zero values, it won’t be used to build query conditions.

Here is an example of what I am trying to do :

type Dog struct {
  ID uuid.UUID
  OwnerID *uuid.UUID
}

The owner ID pointer may be nil.

db.Where("owner_id", nil).Find(&dogs)

But that returns all dogs (I expected this from the doc). I tried doing:

db.Where("owner_id", "NULL").Find(&dogs)

But that returns an empty list.

Is there a way to explicitly search for a NULL value field?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • douchang8219 douchang8219 3年前

    According to the docs, this should work:

    db.Where("owner_id IS NULL").Find(&dogs)
    
    点赞 评论 复制链接分享
  • dongpu5874 dongpu5874 3年前

    You were close in your original attempt. You can also achieve your desired result by writing the query as below.

    db.Where("owner_id = ?", "NULL").Find(&dogs)
    
    点赞 评论 复制链接分享