Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GORM db.First print log automatically

Tags:

go-gorm

I am using the latest GORM v2.

When I use db.First(&AoiArea{}), it triggers a record not found error output in the log if nothing is found.

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

Automatic O/P from First:

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

Is there any way to prevent this default log?

I see there is a similar question here https://gorm.io/docs/error_handling.html#comment-5083714457 in their documentation Q&A but no appropriate answer.

like image 948
Arif Avatar asked Oct 18 '25 13:10

Arif


1 Answers

Yes, First will always print the error log.

If you want to avoid the ErrRecordNotFound error, you could use Find like db.Limit(1).Find(&user), the Find method accepts both struct and slice data

doc is here: https://gorm.io/docs/query.html

You can try this

db.Limit(1).Find(&AoiArea{})
like image 52
AlexanderXing Avatar answered Oct 20 '25 11:10

AlexanderXing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!