Gorm NOT NULL 约束 STILL PASSES FOR 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")

}

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


慕斯709654
浏览 482回答 3
3回答

胡子哥哥

首先,您应该检查迁移是否已正确运行,这意味着在数据库中创建了列not null约束。user_id, task_id, job_id, ..其次,您必须使用指针,因为golang有一个概念zero value意味着int, float, string,如果您没有分配任何值,则相应地具有bool默认值, , 。但是如果你使用指针那么这个字段将最终将在数据库中发送。如果对该列有约束,则会发生错误。00.0""falsenilNULLNOT NULL

九州编程

您需要为此使用sql.NullIntxxnot null或 int/float 指针,因为 int/float 的默认/空值为 0,这是针对数据库的。所以 gorm 和 DB 将允许它作为非空值传递。类似地,对于string必须使用*string或sql.NullStting作为默认值的类型string是“”(空白字符串)而不是零。

慕桂英4014372

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)祝你学习顺利!
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go