如何检查值是否存在于数据库中?

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

How to check if the value is existing in DB

问题

如何检查我要插入的值在数据库中是否存在?

假设我有以下代码:

type studentRepository struct {
	db *gorm.DB
}

type Student struct {
    Name string     `json:"name"`
    Age int         `json:"age"`
}

func (s student) CreateStudent(v Student) (*Student, error) {
    db := p.db.Create(&v)
    return &v, db.Error
}

我想创建一个新的学生,但不能与其他学生具有相同的姓名。如何检查我要插入的姓名在数据库中不存在?

例如:
StudentList = {Messi, Ronaldo, Tevez}
WantToInsert = {Ronaldo}
结果 = 不可能发生,因为Ronaldo已经存在于列表中。

英文:

How do I check if the value that I want to insert is existing in database or not

Let say I have


type studentRepository struct {
	db *gorm.DB
}

type Student struct {
    Name string     `json:"name"`
    Age int         `json:"age"`
}

func(s student) CreateStudent(v Student) (*Student, error) {
    db := p.db.Create(&v)
	return &v, db.Error
}

I want to create new student but cannot have the same name with other students. How can I check if the name that I want to insert is not existing in the db?

Example: 
StudentList = {Messi, Ronaldo, Tevez}
WantToInsert = {Ronaldo}
Result = Cannot happened because Ronaldo is existing on the list


</details>


# 答案1
**得分**: 3

你可以通过在SQL数据库中创建“unique”约束来防止输入相同的值,Gorm允许在结构体中添加unique关键字:

```go
type Student struct {
    Name string     `json:"name" gorm:"unique"`
    Age int         `json:"age"`
}

你可以参考Gorm的文档了解更多细节:
Gorm索引文档

你还可以为了记录目的捕获重复错误,具体实现取决于你使用的数据库,在使用PostgreSQL的情况下,可以使用以下示例:

err := db.Create(student).Error

if err != nil {
    var pgErr *pgconn.PgError
    if errors.As(err, &pgErr) && (pgErr.Code == "23505") {
        // 在这里处理错误
    }
}
英文:

you can prevent inputting the same value by creating "unique" constraint in your SQL database ,
Gorm allows that adding unique keyword to your struct:

type Student struct {
    Name string     `json:&quot;name&quot; gorm:&quot;unique&quot;`
    Age int         `json:&quot;age&quot;`
}

you can refer to Gorm's documentation for more details:
Gorm indexing documentation

you can also catch duplicate error for logging purposes
the implementation differs depending on the database you're using,
this example works in the case of using Postgresql:

err := db.Create(student).Error

if err != nil {
	var pgErr *pgconn.PgError
	if errors.As(err, &amp;pgErr) &amp;&amp; (pgErr.Code == &quot;23505&quot;) {
		// handle error here
	}
}

huangapple
  • 本文由 发表于 2022年8月10日 15:11:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/73302074.html
匿名

发表评论

匿名网友

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

确定