Your Question
How to add unique constraint on combined multiple columns in gorm.
Structure Look like this
type DumyProject struct {
DumyProjectId int gorm:"type:integer primary key GENERATED ALWAYS AS IDENTITY ( INCREMENT 1 START 1 MINVALUE 1 MAXVALUE 2147483647 CACHE 1 );not null;"
ProjectId int gorm:"type:integer;not null;"
PracticeAreaName string gorm:"type:varchar;not null;"
}
The document you expected this should be explained
Expected answer
I want to add constraint like: CONSTRAINT dummy_project_values_un UNIQUE (dummy_project_id, dummy_field_id)
type DumyProject struct.docx.tar.gz
Comment From: ashupednekar
Use the same unique index on the fields you need to be unique together, like so..
type GroupUserMap struct {
ID int `gorm:"primaryKey"`
GroupID int
Group Groups `uniqueIndex:idx_user_grp_uniq_together"`
UserID int
User Users `uniqueIndex:idx_user_grp_uniq_together"`
}
This will result in indexes like so...
console=# \d group_user_maps;
Table "public.group_user_maps"
Column | Type | Collation | Nullable | Default
----------+--------+-----------+----------+---------------------------------------------
id | bigint | | not null | nextval('group_user_maps_id_seq'::regclass)
group_id | bigint | | |
user_id | bigint | | |
Indexes:
"group_user_maps_pkey" PRIMARY KEY, btree (id)
"idx_user_grp_uniq_together" UNIQUE, btree (group_id, user_id)
Foreign-key constraints:
"fk_group_user_maps_group" FOREIGN KEY (group_id) REFERENCES groups(id)
"fk_group_user_maps_user" FOREIGN KEY (user_id) REFERENCES users(id)
Hope it helps :)
Comment From: Abhishek-Mali-Personal
@ashupednekar This would create a unique index what i really want is to create a unique constraint not a unique index