我遇到了这个库的问题,因为即使给定的输入不在数据库中,这个函数也会返回 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")
}
Run Code Online (Sandbox Code Playgroud)
为什么它总是返回 false,即使字符串为空?
fre*_*yle 11
看起来.RecordNotFound() 由于某种原因已从 SDK 中删除。
现在用它来处理记录未找到错误
dbRresult := userHandler.db.Where("email = ?", email).First(&user)
if errors.Is(dbRresult.Error, gorm.ErrRecordNotFound) {
// handle record not found
}
Run Code Online (Sandbox Code Playgroud)
以下代码应该按您的预期工作:
// 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")
}
Run Code Online (Sandbox Code Playgroud)
正如mkopriva已经提到的ErrRecordNotFound那样,当您使用切片时不会触发。
由于您不需要切片(您的用户名应该是唯一的),我们可以:
引用的不是一部分用户而是单个用户 User{}而不是[]User{}.
使用gorms First()方法而不是Find().
| 归档时间: |
|
| 查看次数: |
2887 次 |
| 最近记录: |