Last active
May 20, 2020 22:42
-
-
Save brunoksato/20a1ef2cbf066513bde4dc91dcb0c2ed 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 { | |
ID uint `json:"id" gorm:"primary_key" settable:"false"` | |
Title string `json:"t" sql:"not null"` | |
RelatedSets []Set `json:"rs,omitempty" gorm:"many2many:related_sets;"` | |
} | |
//struct Set | |
type Set struct { | |
ID uint `json:"id" gorm:"primary_key" settable:"false"` | |
Title string `json:"t" sql:"not null"` | |
Channel *Channel `json:"ch,omitempty" ` | |
ChannelID uint `json:"id-ch" sql:"index;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