duanjin9035 2018-09-30 07:41
浏览 157
已采纳

返回nil struct而不是空struct go-gorm

With the following model:

type User struct {
    UUID string         `gorm:"primary_key"`
    Name string         `gorm:"NOT NULL"`
    CreatedAt time.Time
    UpdatedAt time.Time
}

If you do the following query with go-gorm for a user that does NOT exist:

var user User
db.First(&user)

You end up receiving an empty struct with the date fields populated. Is there a way to instead just receive a nil struct back or am I thinking about this in the wrong way?

  • 写回答

2条回答 默认 最新

  • dongyuans61046 2018-09-30 09:05
    关注

    In gorm you are supposed to check if the record is empty, with a method call:

    if db.First(&user, 77).RecordNotFound() {
        log.Println("UUID:", 77, err)
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • doulai5585 2018-09-30 08:33
    关注

    Add a Pointer function

    func (user User) Pointer() *User {
        var t time.Time
        if user.UUID == "" && user.Name == "" && user.CreatedAt == t && user.UpdatedAt == t {
            return nil
        }
        return &user
    }
    

    and pass it

    var user User
    db.First(user.Pointer())
    
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 关于非编程寻迹小车的分析
  • ¥15 java导出EXCEL这里已经执行成功了,但是流浪器没有下载
  • ¥15 帮我把代码改的能正常运行就行
  • ¥50 有限元修正、模型修正、最小二乘法,详细步骤
  • ¥15 用plc编写梯形程序
  • ¥15 关于#物联网#的问题:新大陆AIOT中,按照手册教程进行添加,设置完成后网关一直不上线,显示Never这是网络服务的信息
  • ¥15 这个要用一维热方程但是我不知道怎么运用这个公式
  • ¥15 OpenFOAM多孔介质传热模型建模
  • ¥15 QT 实现 RSTP 语音对讲功能
  • ¥15 用C语言写的一个程序遇到了两个问题第一是偏移正确但读取不到坐标,第二个问题是自己定义的函数实现不了获取指定进程模块。