Created
May 20, 2020 22:41
-
-
Save brunoksato/94d6c63bcbde0bc2fa58fe52cb67f226 to your computer and use it in GitHub Desktop.
manytomany gorm
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//struct channel | |
type Channel struct { | |
Title string `json:"t" sql:"not null"` | |
RelatedSets []Set `json:"rs,omitempty" gorm:"many2many:related_sets;"` | |
} | |
//struct Set | |
type Set struct { | |
Title string `json:"t" sql:"not null"` | |
} | |
//sql da tabela de ref | |
CREATE TABLE related_sets ( | |
channel_id integer NOT NULL, | |
set_id integer NOT NULL | |
); | |
ALTER TABLE related_sets ADD CONSTRAINT fk_related_sets_set_id FOREIGN KEY (set_id) REFERENCES sets; | |
ALTER TABLE related_sets ADD CONSTRAINT fk_related_sets_channel_id FOREIGN KEY (channel_id) REFERENCES channels; | |
ALTER TABLE related_sets ADD CONSTRAINT related_sets_channel_set_pkey PRIMARY KEY (channel_id, set_id); | |
// preload | |
c.Database.Preload("RelatedSets").First(&ch) | |
// insert | |
err := db.Exec("INSERT INTO related_sets (set_id, channel_id) VALUES (?, ?)", | |
setId, | |
c.ID). | |
Error |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment