GORM 条件查询的第一个示例

huangapple go评论99阅读模式
英文:

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

huangapple
  • 本文由 发表于 2023年6月22日 08:23:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/76527917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定