英文:
GORM First Query with Condition
问题
我想咨询一下关于使用 GORM 的 db.First()
方法的条件查询。
好的,这是一个例子:
if err := repository.db.First(&admin, id).Error; err != nil {
return nil, &response.Error{
Code: 500,
Err: err,
}
}
根据 GORM 的文档这里所述,我知道这是可行的。
但是,这样呢?
if err := repository.db.First(&admin, email).Error; err != nil {
return nil, &response.Error{
Code: 500,
Err: err,
}
}
这样的写法和下面的写法是一样的吗?
err := repository.db.Where("email = ?", email).First(&admin).Error
提前感谢您的回答。
我已经仔细阅读了 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
答案1
得分: 3
First
方法用于获取符合条件的第一条记录,默认会使用主键字段(id
)进行检查。
repository.db.First(&admin, id)
在这里,它将生成一个查询语句:SELECT * FROM admin WHERE id = :id
repository.db.First(&admin, "an-email@gmail.com")
这与repository.db.Where("email = ?", email).First(&admin)
不同,
这里也会使用id
字段进行条件检查。
SELECT * FROM admin WHERE id = an-email@gmail.com
- 会引发错误
相反,你可以尝试这个或者与where
一样的方式:
db.First(&admin, "email = ?", "an-email@gmail.com")
因为这将使用email
字段进行条件检查。
你可以启用调试模式,它会显示查询语句:
db = db.Debug()
参考资料:
希望对你有所帮助。
英文:
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, "an-email@gmail.com")
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 = an-email@gmail.com
- will raise an error
instead, you can try this or the same you have with where
db.First(&admin, "email = ?", "an-email@gmail.com")
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论