英文:
GO pg prevent default value
问题
结构示例
type Car struct {
ID uint64
Required bool `pg:"required,notnull"`
Name string `pg:"name"`
}
迁移:
BEGIN;
ALTER TABLE cars ADD COLUMN required BOOLEAN NOT NULL DEFAULT true;
END;
当我创建car结构时:
car := Car{Name: "Name", Required: false}
当我尝试通过以下方式添加一些新的car:
_, err := r.db.Model(&car).Insert()
SQL查询如下所示:
INSERT INTO "cars" ("id", "name", "required") VALUES (DEFAULT, "Name", DEFAULT)
主要问题是car的required字段被设置为false,但在插入时它会更改为DEFAULT(true)。
英文:
Struct sample
type Car struct {
ID uint64
Required bool `pg:"required,notnull"`
Name string `pg:"name"`
}
Migration:
BEGIN;
ALTER TABLE cars ADD COLUMN required BOOLEAN NOT NULL DEFAULT true;
END;
When I create car struct:
car = Car{Name:"Name",Required:false}
When i'm trying to add some new car by writing:
_, err = r.db.Model(&car).Insert()
SQL Query looks like this:
INSERT INTO "cars" ("id", "name", "required") VALUES (DEFAULT, "Name", DEFAULT)
The main problem that car has required field set as false, but when I inserting it - it changes to DEFAULT (true).
答案1
得分: 2
因为值false
将被解读为null值。因为null值会将您的数据更改为默认值(TRUE)。
您必须将结构更改为以下形式:
type Car struct {
ID uint64
Required *bool `pg:"required,notnull,default:true"`
Name string `pg:"name"`
}
并像这样定义结构:
required := false
car = Car{Name:"Name", Required: &required}
或者您还可以在结构中使用数据类型sql.NullBool
:
type Car struct {
ID uint64
Required sql.NullBool `pg:"required,notnull,default:true"`
Name string `pg:"name"`
}
car = Car{Name:"Name", Required: sql.NullBool{Bool: false, Valid: true}}
英文:
Because the value false
will be read as a null value. Because null value your data will be change to the default value (TRUE)
You must change the struct to like this
type Car struct {
ID uint64
Required *bool `pg:"required,notnull,default:true"`
Name string `pg:"name"`
}
and define struct like this
required := false
car = Car{Name:"Name", Required: &required}
or you can also use data type sql.NullBool
in your struct
type Car struct {
ID uint64
Required sql.NullBool `pg:"required,notnull,default:true"`
Name string `pg:"name"`
}
car = Car{Name:"Name", Required: sql.NullBool{Bool: false, Valid: true}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论