英文:
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:"name" gorm:"unique"`
Age int `json:"age"`
}
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, &pgErr) && (pgErr.Code == "23505") {
// handle error here
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论