<p>I can't work out the best way to add an association to a model. I have the following structs</p>
<pre><code>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"`
}
</code></pre>
<p>Below is an example of data i have seeded the DB with</p>
<pre><code>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},
},
},
</code></pre>
<p>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?</p>
<p>Thanks,
Justin</p>
<hr/>**评论:**<br/><br/>hobbified: <pre><p>If you don't want it to think that a record is new and needs to be inserted, you need to set the ID field in the struct to the ID of the existing row (usually you do this by loading the row from the DB in the first place, but not necessarily. <code>FirstOrCreate</code> can be helpful here.)</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
0 回复
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传