3 回答
TA贡献1825条经验 获得超6个赞
首先,您应该检查迁移是否已正确运行,这意味着在数据库中创建了列
not null
约束。user_id, task_id, job_id, ..
其次,您必须使用指针,因为
golang
有一个概念zero value
意味着int
,float
,string
,如果您没有分配任何值,则相应地具有bool
默认值, , 。但是如果你使用指针那么这个字段将最终将在数据库中发送。如果对该列有约束,则会发生错误。0
0.0
""
false
nil
NULL
NOT NULL
TA贡献1785条经验 获得超4个赞
您需要为此使用sql.NullIntxxnot null
或 int/float 指针,因为 int/float 的默认/空值为 0,这是针对数据库的。
所以 gorm 和 DB 将允许它作为非空值传递。
类似地,对于string
必须使用*string
或sql.NullStting
作为默认值的类型string
是“”(空白字符串)而不是零。
TA贡献1871条经验 获得超13个赞
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
)
祝你学习顺利!
- 3 回答
- 0 关注
- 306 浏览
添加回答
举报