【发布时间】:2021-02-20 19:10:26
【问题描述】:
在创建 CLI 应用时,我遇到了使用 GORM 批量保存数据的问题。
具体来说,使用包含值的切片保存为多对多关系。
命令eddie track mood -q 9 --tags=one,two,three,four -i 静态创建如下:
two := &schema.Record{
Type: "mood",
Quality: 9,
Tags: []schema.Tag{
{Name: "one"},{Name: "two"},{Name: "three"},{Name: "four"},
},
Important: false,
}
但是...对于一个 for/range 循环,我只选择了最后一个(我想这很明显是为什么),所以 db.Create(&two) 返回一个标签,而不是多个标签。
var t []schema.Tag
for _, v := range tags {
t = []schema.Tag{{Name: v}}
}
r := &schema.Record{
Type: "mood",
Quality: q,
Tags: t,
Important: i,
}
database.Create(&r)
fmt.Printf("You rated your mood a %d.\n", q)
fmt.Println("Record ID:", r.ID)
fmt.Println("Tags:", r.Tags)
return err
You rated your mood a 9.
Record ID: 11
Tags: [{four}]
我考虑过的事情:
- 我不想将“一、二、三、四”保存为单个输入,稍后再解析
- 批量更新不会保留 ID、关系(键),因此(根据我的理解)这应该是单个
db.Create()或使用省略,然后立即更新 - 我是 Go 新手(过去 8 年的 PHP 开发人员),所以我需要一些帮助!
- 我的结构可能设置不正确?
当返回切片的值时,如何在 GORM 中批量更新记录?
【问题讨论】: