Search code examples
goormgo-gorm

GORM First Query with Condition


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


Solution

  • 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

    Hope this helps