[英]Select exists with GORM
I want to check if a row exists in a database table or not.我想检查数据库表中是否存在一行。 I first used this approach:
我首先使用这种方法:
type MyStruct struct {
ID uint32
Key string
Value string
}
var result MyStruct
err := db.
Where("id = ? AND `key` = ? AND `value` = 0", myID, myKey).
First(&result).
Error
if err != nil {
if err == gorm.ErrRecordNotFound {
logrus.Error("ErrRecordNotFound")
}
logrus.Errorf("Other DB error: %s", err.Error())
}
But I want to achieve this by writing a raw SQL. I tried following:但我想通过编写原始 SQL 来实现这一点。我尝试了以下操作:
var result bool
db.Raw("SELECT EXISTS(SELECT 1 FROM my_table WHERE id = ? AND `key` = ? AND `value` = ?)",
myID, myKey, "0").Scan(&result)
But I get this error:但我收到此错误:
unsupported destination, should be slice or struct.
I also tried to use method Exec
and got the same error.我也尝试使用方法
Exec
并得到了同样的错误。
Note that the variable db
is a *gorm.DB
instance.请注意,变量
db
是一个*gorm.DB
实例。
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如果你想避免 ErrRecordNotFound 错误,你可以使用 Find like db.Limit(1).Find(&user),Find 方法接受结构和切片数据
r := db.
Where("id = ? AND `key` = ? AND `value` = 0", myID, myKey).
Limit(1).
Find(&result)
r.Error
// handle error
exists := r.RowsAffected > 0
Your result
should be either a struct or a slice, not a bool.您的
result
应该是结构或切片,而不是布尔值。 More information at here: https://gorm.io/docs/sql_builder.html#Raw-SQL更多信息在这里: https://gorm.io/docs/sql_builder.html#Raw-SQL
This should work:这应该有效:
var result struct {
Found bool
}
db.Raw("SELECT EXISTS(SELECT 1 FROM my_table WHERE id = ? AND `key` = ? AND `value` = ?) AS found",
myID, myKey, "0").Scan(&result)
Another way you might check for existence is using Count
:您可以检查是否存在的另一种方法是使用
Count
:
count := int64(0)
err := db.Model(&MyStruct{}).
Where("id = ? AND key = ? AND value = 0", myID, myKey).
Count(&count).
Error
// handle error
exists := count > 0
maybe a late reply, but I wanna share the answer which I found, it's possible to scan directly into a bool.也许回复晚了,但我想分享我找到的答案,可以直接扫描成布尔值。 Name of the variable should be changed to a capital letter to achieve this.
变量的名称应更改为大写字母以实现此目的。
ex:前任:
var Found bool
db.Raw("SELECT EXISTS(SELECT 1 FROM magic_table WHERE magic_field1 = ? AND magic_field2 = ? AND magic_field3 = ?) AS found",
valOfMagicField1, valOfMagicField2, valOfMagicField3).Scan(&Found)
You can try the following approach您可以尝试以下方法
var exists bool
err = db.Model(model).
Select("count(*) > 0").
Where("id = ?", id).
Find(&exists).
Error
For me trying this with find
did not work, the best approach I found is as follows:对我来说,用
find
尝试这个没有用,我找到的最佳方法如下:
res := db.Model(&MyStruct{}).
Where("id = ? AND key = ? AND value = 0", myID, myKey).
First(&result)
if errors.Is(res.Error, gorm.ErrRecordNotFound) {
// user does not exists
} else if res.Error != nil {
// some other problem
return res.Error
}
That should work:那应该工作:
var result bool
db.Raw("SELECT true FROM my_table WHERE id = ? AND key = ? AND value = ?)",
myID, myKey, "0").Scan(&result)
if result {
// exists
} else {
// does not exist
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.