I can't work out the best way to add an association to a model. I have the following structs
type Beer struct {
ID uint `json:"id"`
Name string `json:"name" gorm:"not null;" sql:"unique"`
Description string `json:"description" gorm:"not null;"`
ImageURL string `json:"image_url"`
AlcoholContent float64 `json:"alcohol_content, default:0"`
Featured bool `json:"featured"`
BrewStart time.Time `json:"brew_start"`
BrewEnd time.Time `json:"brew_end"`
Brewers []Brewer `gorm:"many2many:beer_brewers" json:"brewers"`
}
type Brewer struct {
ID uint `json:"id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
Title string `json:"title"`
Featured bool `json:"featured"`
Beers []Beer `gorm:"many2many:beer_brewers" json:"beers"`
}
Below is an example of data i have seeded the DB with
Beer{
Name: "some pale ale",
Description: "a description of some pale ale",
ImageURL: "http://via.placeholder.com/350x150",
AlcoholContent: 4.5,
Featured: false,
BrewStart: utils.ParseTime("30-10-2017 13:00 (AEDT)"),
BrewEnd: utils.ParseTime("14-11-2017 13:00 (AEDT)"),
Brewers: []Brewer{
Brewer{FirstName: "john", LastName: "smith", Title: "bottle shaker", Featured: false},
Brewer{FirstName: "joe", LastName: "bloggs", Title: "bottle maker", Featured: true},
},
},
Beer{
Name: "some lager",
Description: "a description of some pale ale",
ImageURL: "http://via.placeholder.com/350x150",
AlcoholContent: 4.5,
Featured: false,
BrewStart: utils.ParseTime("30-10-2017 13:00 (AEDT)"),
BrewEnd: utils.ParseTime("14-11-2017 13:00 (AEDT)"),
Brewers: []Brewer{
Brewer{FirstName: "john", LastName: "smith", Title: "bottle shaker", Featured: false},
Brewer{FirstName: "joe", LastName: "bloggs", Title: "bottle maker", Featured: true},
},
},
However the above creates duplicate Brewers in the Brewer table. My question is, what is the best way to reference a Brewer that already exists but not create another Brewer item in the Brewer table?..and also what is the best way to Append a new Brewer into a Beer collection?
Thanks, Justin