Skip to content

Instantly share code, notes, and snippets.

@brunoksato
Last active May 20, 2020 22:42
Show Gist options
  • Save brunoksato/20a1ef2cbf066513bde4dc91dcb0c2ed to your computer and use it in GitHub Desktop.
Save brunoksato/20a1ef2cbf066513bde4dc91dcb0c2ed to your computer and use it in GitHub Desktop.
manytomany gorm
//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