I have an issue when I try to create a model in the database using GORM and Gin.
This is my code in the controller:
func CreateSymbol(c *gin.Context) {
var payload models.Symbol
if err := c.ShouldBind(&payload); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
return
}
fmt.Println(payload)
symbol, err := repositories.CreateSymbol(payload)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"message": err.Error()})
return
}
c.JSON(http.StatusOK, gin.H{"data": symbol})
}
And this is my function in the repository:
func CreateSymbol(model models.Symbol) (models.Symbol, error) {
result := boot.DB.Create(&model)
if result.Error != nil {
return models.Symbol{}, result.Error
}
return model, nil
}
And this is my model and migration:
type Symbol struct {
gorm.Model
Code string
Icon string
Status string
MaxLeverage uint32
Precision uint32
MinQty float64
}
type Symbol struct {
gorm.Model
Code string `gorm:"index;unique"`
Precision uint32
MaxLeverage uint32
MinQty float64
Icon string
Status string `gorm:"index"`
}
This is my last record in the database:
{
"ID": 11,
"CreatedAt": "2023-02-22T14:51:27.52Z",
"UpdatedAt": "2023-02-22T14:51:27.52Z",
"DeletedAt": null,
"Code": "KLC2",
"Icon": "/images/klc1.png",
"Status": "inactive",
"MaxLeverage": 20,
"Precision": 4,
"MinQty": 0
}
When I completed my code and ran it from Postman, everything seemed OK until I accidentally create another symbol that duplicate Code
field. The error was returned:
{
"message": "Error 1062 (23000): Duplicate entry 'KLC2' for key 'symbols.code'"
}
Then, I changed the request data. The error is gone, but the symbol was created with ID is 13 that I expected is 12.
{
"data": {
"ID": 13,
"CreatedAt": "2023-02-22T16:08:08.827Z",
"UpdatedAt": "2023-02-22T16:08:08.827Z",
"DeletedAt": null,
"Code": "KLC3",
"Icon": "/images/klc3.png",
"Status": "inactive",
"MaxLeverage": 20,
"Precision": 4,
"MinQty": 0
}
}
I am not sure what I am doing wrong.