【问题标题】:GORM db.First print log automaticallyGORM db.First 自动打印日志
【发布时间】:2021-09-17 03:27:24
【问题描述】:

我使用的是最新的GORM v2

当我使用db.First(&AoiArea{})时,如果没有找到,它会在日志中触发记录未找到错误输出。

    if err := db.First(&AoiArea{}).Error; errors.Is(err, gorm.ErrRecordNotFound) {
        // Do something
    }

来自First的自动O/P:

2021/09/17 09:02:24 ←[31;1mE:/xyz-api/models/utils.go:47 ←[35;1mrecord not found ←[0m←[33m[0.000ms] ←[34;1m[rows:0]←[0m SELECT * FROM "aoi_area" ORDER BY "aoi_area"."id" LIMIT 1

有什么办法可以阻止这个默认日志吗?

我在他们的文档问答中看到https://gorm.io/docs/error_handling.html#comment-5083714457 有一个类似的问题,但没有适当的答案。

【问题讨论】:

    标签: go-gorm


    【解决方案1】:

    是的,First 将始终打印错误日志。

    如果你想避免ErrRecordNotFound错误,你可以像db.Limit(1).Find(&user)一样使用FindFind方法接受结构和切片数据

    文档在这里:https://gorm.io/docs/query.html

    你可以试试这个

    db.Limit(1).Find(&AoiArea{})
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-07-08
      • 1970-01-01
      • 2011-09-01
      • 2021-12-09
      • 2015-07-25
      • 1970-01-01
      • 2017-11-05
      • 1970-01-01
      相关资源
      最近更新 更多