Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GORM First Query with Condition

Tags:

orm

go

go-gorm

I would like to ask regarding GORM db.First() with Condition

Okay, here's an example

if err := repository.db.First(&admin, id).Error; err != nil {
    return nil, &response.Error{
        Code: 500,
        Err:  err,
    }
}

I know for a fact that this is possible because of GORM documentation stated here

But, how about this?

if err := repository.db.First(&admin, email).Error; err != nil {
    return nil, &response.Error{
        Code: 500,
        Err:  err,
    }
}

Does that the same as this? err := repository.db.Where("email = ?", email).First(&admin).Error

Thanks in advance

I have tried to read the GORM documentation thoroughly, and i can't find any statement that my approach could possibly done. So, i ask here in hope to get some enlightment

like image 823
Akhmad Dani Munif Avatar asked Feb 03 '26 04:02

Akhmad Dani Munif


1 Answers

First method is used to get the first record that matches the condition, and it will check with the primary key field (id) by default.

repository.db.First(&admin, id)

At here, it will generate a query as SELECT * FROM admin WHERE id = :id


repository.db.First(&admin, "[email protected]")

This is not same like repository.db.Where("email = ?", email).First(&admin) here also it will check the condition with id field.

SELECT * FROM admin WHERE id = [email protected] - will raise an error

instead, you can try this or the same you have with where

db.First(&admin, "email = ?", "[email protected]")

As this will check the condition with email field.

You can enable the debug mode and it will show you the queries

db = db.Debug()

See also

  • Retrieving objects with primary key
  • Logger

Hope this helps

like image 74
PRATHEESH PC Avatar answered Feb 05 '26 20:02

PRATHEESH PC



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!