Gorm NOT NULL 约束仍然在数据库 Golang 中传递 NULL 值



在我的结构中,我有以下内容

type Task struct {
gorm.Model
Id         int       `json:"id" gorm:"primaryKey;AUTO_INCREMENT"`
UserId int       `json:"user_id" gorm:"Index;not null" validate:"required"`
TaskId     int       `json:"task_id" gorm:"Index;not null" validate:"required"`
JobId      int       `json:"job_id" gorm:"not null" validate:"required"`
Latitude   float64   `json:"latitude" gorm:"not null" validate:"required"`
Longitude  float64   `json:"longitude" gorm:"not null" validate:"required"`
StartAt    time.Time `json:"start_at"`
EndAt      time.Time `json:"end_at"`
CreatedAt  time.Time
UpdatedAt  time.Time
}

我有这个功能,可以通过以下方式保存到表中

{   "user_id": 1,
"location":[5748.5445, 89790.454],
"latitude": 89790.454,
"longitude": 5748.5445,
"startAt":  "2030-10-30T10:58:00.000Z",
"endAt": "2031-10-30T10:58:00.000Z"
}
func CreateTask(c *fiber.Ctx) error {
var opentask models.JobOpenTask

if err := c.BodyParser(&opentask); err != nil {
return c.Status(400).JSON(err.Error())
}

db.DB.Db.Create(&opentask)
return c.Status(200).JSON("OK")
}

当它运行时,它仍然将记录保存在数据库中,但我希望它在尝试保存时会抛出并出错,因为它在我的结构中not null,但为什么它能够保存到 Db 而不会抛出错误?

你需要使用 sql。NullIntxx 或 int/float 指针,因为 int/float 的默认/空值为 0,这对数据库not null

因此,gorm 和 DB 将允许它作为非空值传递。

同样,对于必须使用*stringsql.NullSttingstring类型,默认值为string是 "(空白字符串)而不是 nil。

  • 首先,您应该检查迁移是否已正常运行not null这意味着user_id, task_id, job_id, ..列的约束是在数据库中创建的。
  • 其次,你必须使用指针,因为golang有一个zero value的概念,这意味着intfloatstringbool的默认值是00.0""false,如果你不分配任何值。但是如果你使用指针,那么这个字段将被nil,最终NULL将在数据库中发送。如果该列有NOT NULL约束,则会发生错误。
  • null 只需申请指针
  • gorm.Model包括
type Model struct {
ID        uint `gorm:"primarykey"`
CreatedAt time.Time
UpdatedAt time.Time
DeletedAt DeletedAt `gorm:"index"`
}

不需要在结构中声明Id, CreatedAt, UpdatedAt

  • 将结构更正为波纹管:
type Task struct {
gorm.Model
UserId     int       `json:"user_id"`
TaskId     int       `json:"task_id"`
JobId      int       `json:"job_id"`
Latitude   float64   `json:"latitude"`
Longitude  float64   `json:"longitude"`
StartAt    time.Time `json:"start_at"`
EndAt      time.Time `json:"end_at"`
}
  • 标签和最佳实践是由数据库控制,其中列定义不为空约束

  • 当你创建表时,AUTO_INCREMENT应该在数据库上创建,这需要由数据库控制,而不是通过语言控制

  • 将表声明为波纹管:

create table tasks (
int primary key AUTO_INCREMENT,
user_id int not null, 
task_id int not null,
job_id int not null,
latitude int not null,
longitude int not null,
start_at datetime,
created_at datetime,
updated_at datetime
)

祝你学习顺利!

最新更新