【发布时间】:2021-04-09 02:59:07
【问题描述】:
我正在构建一个非常小的应用程序来学习 Golang,我正在使用 Echo 与 GORM 和 PostgreSQL 进行简单的 CRUD。问题是我在创建新用户时总是收到这个ERROR: null value in column "id" of relation "users" violates not-null constraint (SQLSTATE 23502 错误。我在documentation 上进行了搜索,但似乎 GORM 总是应该自动处理 ID 创建和其他内容。
这是我的模型:
type User struct {
ID int64 `json:"id" gorm:"primarykey"`
Name string `json:"name"`
Email string `json:"email"`
}
这是我用于创建用户的函数:
func CreateUser(c echo.Context) error {
// Parse input data
user := &models.User{}
if err := c.Bind(user); err != nil {
errorMessage := lib.Message{Message: "Failed to parse new user data: " + err.Error()}
return c.JSON(http.StatusInternalServerError, errorMessage)
}
fmt.Println(user) // debug
// Creating new entry
db := storage.GetDBInstance()
if err := db.Create(user).Error; err != nil {
errorMessage := lib.Message{Message: "Failed to create new user: " + err.Error()}
return c.JSON(http.StatusInternalServerError, errorMessage)
}
return c.JSON(http.StatusCreated, user)
}
这是我用于测试的命令:
curl -X POST \
-H 'Content-Type: application/json' \
-d '{"name":"Joe Smith", "email":"joe.smith@example.com"}' \
localhost:1323/users
最后,这是我得到的输出:
⇨ http server started on [::]:1323
&{0 Joe Smith joe.smith@example.com}
2021/03/12 13:56:10 /home/gabriel-milan/go/src/github.com/gabriel-milan/echo-rest-api/api/controllers/user.go:89 ERROR: null value in column "id" of relation "users" violates not-null constraint (SQLSTATE 23502)
[2.749ms] [rows:0] INSERT INTO "users" ("name","email") VALUES ('Joe Smith','joe.smith@example.com') RETURNING "id"
{"time":"2021-03-12T13:56:10.125834131-03:00","id":"","remote_ip":"::1","host":"localhost:1323","method":"POST","uri":"/users","user_agent":"curl/7.64.0","status":500,"error":"","latency":3377762,"latency_human":"3.377762ms","bytes_in":53,"bytes_out":144}
在我的模型声明中,我还尝试过gorm:"primaryKey"、gorm:"primary_key"、将默认值设置为 UUID 函数、继承自 gorm.Model...但似乎都不起作用。
我的要求(版本检查):
require (
github.com/labstack/echo/v4 v4.2.1
github.com/lib/pq v1.6.0 // indirect
gorm.io/driver/postgres v1.0.8 // indirect
gorm.io/gorm v1.21.3 // indirect
)
【问题讨论】:
标签: postgresql go go-gorm