如何阻止 Go Gorm 在 Postgres 中对我的自引用外键强制施加非空约束
时间:2024-04-17
浏览:112
作者:佚名
IT行业相对于一般传统行业,发展更新速度更快,一旦停止了学习,很快就会被行业所淘汰。所以我们需要踏踏实实的不断学习,精进自己的技术,尤其是初学者。今天golang学习网给大家整理了《如何阻止 Go Gorm 在 Postgres 中对我的自引用外键强制施加非空约束》,聊聊,我们一起来看看吧!
问题内容
我需要创建一个在 gorm 中引用自身的表,但无法弄清楚为什么它对我强制使用 not null 约束。我完全被难住了。我该如何解决这个问题?我正在使用 gorm 提供的 automigrate 功能来创建表。当我删除外键约束时,not null 约束就会消失,但这不是我想要的。
编辑:我专门使用包“gorm.io/gorm”,而不是 github 上的包。这也是唯一给我带来问题的表,任何其他具有引用其他表的外键的表都会按预期工作。
使用外键
type user struct {
id *int `gorm:"primarykey; type:serial"`
username string `gorm:"type: varchar(32) not null unique"`
password string `gorm:"type: varchar(128) not null"`
referredby *int
referrer *user `gorm:"foreignkey:referredby;constraint:onupdate:cascade,ondelete:set null"`
}
根据 pgadmin 使用外键生成的 sql
-- table: public.users
-- drop table public.users;
create table public.users
(
id integer not null default nextval('users_id_seq'::regclass),
username character varying(32) collate pg_catalog."default" not null,
password character varying(128) collate pg_catalog."default" not null,
referred_by integer not null default nextval('users_referred_by_seq'::regclass),
constraint users_pkey primary key (id),
constraint users_username_key unique (username),
constraint fk_users_referrer foreign key (referred_by)
references public.users (id) match simple
on update cascade
on delete set null
)
tablespace pg_default;
alter table public.users
owner to msmf;
没有外键
// user model. referredby is self referencing foreign key
type user struct {
id *int `gorm:"primarykey; type:serial"`
username string `gorm:"type: varchar(32) not null unique"`
password string `gorm:"type: varchar(128) not null"`
referredby *int
}
在不告诉 gorm 有外键的情况下生成 sql
-- Table: public.users
-- DROP TABLE public.users;
CREATE TABLE public.users
(
id integer NOT NULL DEFAULT nextval('users_id_seq'::regclass),
username character varying(32) COLLATE pg_catalog."default" NOT NULL,
password character varying(128) COLLATE pg_catalog."default" NOT NULL,
referred_by bigint,
CONSTRAINT users_pkey PRIMARY KEY (id),
CONSTRAINT users_username_key UNIQUE (username)
)
TABLESPACE pg_default;
ALTER TABLE public.users
OWNER to msmf;解决方案
显然 type:serial 标签可以做到这一点。如果您删除它,则非空约束也不会存在:
type User struct {
ID uint `gorm:"primarykey"`
Username string `gorm:"type: varchar(32) not null unique"`
Password string `gorm:"type: varchar(128) not null"`
ReferredBy *int
Referrer *User `gorm:"foreignKey:ReferredBy;constraint:OnUpdate:CASCADE,ONDELETE:SET NULL;"`
}
今天关于《如何阻止 Go Gorm 在 Postgres 中对我的自引用外键强制施加非空约束》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
站内热门
最新文章
11.27
11.27
热门专题
