gorm使用find方法返回为空。

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

gorm use the find rerurn empty

问题

我使用find方法来查找一些记录,但当我发送错误的条件时,它应该返回ErrRecordNotFound,但它返回了一个空的结构体。

var projectSetBudget domain.ProjectSetBudget
filter := &domain.ProjectSetBudget{}
filter.TenantID = tenantID
filter.ID = ProjectSetBudgetID
res := r.db.Where(filter).Find(&projectSetBudget)

我只是打印了信息:

zap.S().Info(errors.Is(res.Error, gorm.ErrRecordNotFound))

它打印出false,并返回了空的结构体:

{
    "ID": 0,
    "CreatedAt": "0001-01-01T00:00:00Z",
    "UpdatedAt": "0001-01-01T00:00:00Z",
    "DeletedAt": null,
    "title": ""
}
英文:

I use the find method to find some records,but when I send the wrong condition.it should return the
ErrRecordNotFound,but it return a empty struct

var projectSetBudget domain.ProjectSetBudget
filter := &domain.ProjectSetBudget{}
filter.TenantID = tenantID
filter.ID = ProjectSetBudgetID
res := r.db.Where(filter).Find(&projectSetBudget)

i just print the info

zap.S().Info(errors.Is(res.Error, gorm.ErrRecordNotFound))

it print false

and return the empty struct

{
    "ID": 0,
    "CreatedAt": "0001-01-01T00:00:00Z",
    "UpdatedAt": "0001-01-01T00:00:00Z",
    "DeletedAt": null,
    "title": "",
}

答案1

得分: 2

GORM提供了First、Take、Last方法来从数据库中检索单个对象,在查询数据库时会添加LIMIT 1条件,如果未找到记录,它将返回错误ErrRecordNotFound。
https://gorm.io/docs/query.html

只有First、Take、Last方法,而find方法没有,如果使用First、Take、Last,如果找不到记录会返回ErrRecordNotFound。

First、Take、Last有以下代码,但find方法没有,find方法会查找不止一个记录,所以你可以通过计数来判断是否找到:

tx.Statement.RaiseErrorOnNotFound = true
英文:

GORM provides First, Take, Last methods to retrieve a single object from the database, it adds LIMIT 1 condition when querying the database, and it will return the error ErrRecordNotFound if no record is found.
https://gorm.io/docs/query.html

only First, Take, Last methods but find
if you use First, Take, Last there will be ErrRecordNotFound

First, Take, Last have folow code, but find have not, find will find not only one, so you can know it found or not by count:

tx.Statement.RaiseErrorOnNotFound = true

huangapple
  • 本文由 发表于 2021年8月17日 10:19:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/68810961.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定