如何更新有关与Gorm插入冲突的嵌套字段?
我有两种模型,即字典和字典记录,并带有词典上的外键。
type DictionaryRecord struct {
Id string `gorm:"primaryKey"`
Name string
DictionaryId string
}
type Dictionary struct {
Id string `gorm:"primaryKey"`
Name string
Records []DictionaryRecord
}
我想确保在创建带有嵌套记录的字典时,请在UpSert期间反映更改。
package main
import (
// Sqlite driver based on GGO
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
func main() {
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
if err != nil {
panic(err)
}
db.AutoMigrate(
&DictionaryRecord{},
&Dictionary{},
)
db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
DoUpdates: clause.AssignmentColumns([]string{"name"}),
}).Create(&Dictionary{
Name: "AAAAA",
Id: "e831ab86-db60-4a71-ba63-f20a181cd69b",
Records: []DictionaryRecord{
{
Id: "66f73e9b-61b8-4bc9-941d-80d7fd80f8f4",
Name: "will be updated",
},
},
})
}
您如何指定必须更新dictionaryRecord
中的列名?
I've got two models, Dictionary and DictionaryRecord with a foreign key on Dictionary.
type DictionaryRecord struct {
Id string `gorm:"primaryKey"`
Name string
DictionaryId string
}
type Dictionary struct {
Id string `gorm:"primaryKey"`
Name string
Records []DictionaryRecord
}
I'd like to make sure that when creating a dictionary with a nested record changed, to have the change reflected during the upsert.
package main
import (
// Sqlite driver based on GGO
"gorm.io/driver/sqlite"
"gorm.io/gorm"
"gorm.io/gorm/clause"
)
func main() {
db, err := gorm.Open(sqlite.Open("gorm.db"), &gorm.Config{})
if err != nil {
panic(err)
}
db.AutoMigrate(
&DictionaryRecord{},
&Dictionary{},
)
db.Clauses(clause.OnConflict{
Columns: []clause.Column{{Name: "id"}},
DoUpdates: clause.AssignmentColumns([]string{"name"}),
}).Create(&Dictionary{
Name: "AAAAA",
Id: "e831ab86-db60-4a71-ba63-f20a181cd69b",
Records: []DictionaryRecord{
{
Id: "66f73e9b-61b8-4bc9-941d-80d7fd80f8f4",
Name: "will be updated",
},
},
})
}
How do you specify that the column name in the DictionaryRecord
must be updated?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以尝试使用指针吗
can you try use pointer