モデルに関連付けを追加する最良の方法はありません。私は、次の構造体以下Go GORM many2Many issue
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"`
}
を有する上記のブリューワー・テーブル内の重複醸造を作成しかし、私は
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},
},
},
とDBを播種したデータの一例です。私の質問は、既に存在するBrewerを参照するのに、Brewerテーブルに別のBrewerアイテムを作成する最良の方法は何ですか?また、新しいBrewerをBeerコレクションに追加する最良の方法は何ですか?
おかげで、 ジャスティン
返信いただきありがとうございました。それは素晴らしいアイデアです。 – RuNpiXelruN