GO pg 阻止默认值

huangapple go评论76阅读模式
英文:

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}}

huangapple
  • 本文由 发表于 2022年3月19日 00:02:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/71529912.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定