Skip to content

Instantly share code, notes, and snippets.

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