没有行时RecordNotFound返回false

时间:2018-08-28 21:01:54

标签: go go-gorm

我遇到this library的问题,因为即使给定的输入不在数据库中,该函数也会返回false,而实际上它应该返回true。

type User struct {
    ID          uint      `gorm:"primary_key"`
    Username    string    `json:",omitempty"`
    Password    string    `json:",omitempty"`
    CreatedAt   time.Time `json:",omitempty"`
}

b, err := db.Con()
if err != nil {
    log.Panic(err)
}

defer db.Close()

// We want an empty struct
// Otherwise it will trigger the unique key constraint
user := []User{}

// Check if the username is taken
// BUX, MUST FIX: This always returns false for some reason
if db.Where(&User{Username: "MyUsername"}).Find(&user).RecordNotFound() == false {
    fmt.Println("Username found")
}

为什么即使字符串为空,它也总是返回false?

3 个答案:

答案 0 :(得分:4)

嗨,Jeffrey欢迎来到Stack Overflow的go部分。

以下代码应按预期工作:

// We want an empty struct
user := User{} // We expect to have one (or no) user returned.

// Check if the username is taken
// Notice the use of First() instead of Find()
if !db.Where("username = ?", "MyUsername").First(&user).RecordNotFound() {
    fmt.Println("Username found, here's the user:", user)
} else {
    fmt.Println("Username not found")
}

正如mkopriva所述,在使用切片时,ErrRecordNotFound不会触发。

由于您不需要切片(您的用户名应该是唯一的),我们可以:

  1. 引用不是切片用户,而是单个用户 User{},而不是[]User{}

  2. 使用gorms First()方法代替Find()

答案 1 :(得分:1)

看起来 .RecordNotFound() 出于某种原因已从 SDK 中删除。

现在用它来处理记录未找到的错误

dbRresult := userHandler.db.Where("email = ?", email).First(&user)
if errors.Is(dbRresult.Error, gorm.ErrRecordNotFound) {
    // handle record not found
}

答案 2 :(得分:0)

看起来 .RecordNotFound() 出于某种原因已从 SDK 中删除。

现在用它来处理记录未找到的错误

dbRresult := userHandler.db.Where("email = ?", email).First(&user)
if errors.Is(dbRresult.Error, gorm.ErrRecordNotFound) {
    // handle record not found
}

Documentation