英文:
How to update nested fields on insert conflict with Gorm?
问题
我已经翻译了你提供的内容,请查看以下翻译结果:
我有两个模型,Dictionary(字典)和DictionaryRecord(字典记录),其中DictionaryRecord有一个指向Dictionary的外键。
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 (
// 基于GGO的Sqlite驱动
"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: "将被更新",
},
},
})
}
你如何指定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?
答案1
得分: 2
你可以尝试使用指针:
type DictionaryRecord struct {
Id string `gorm:"primaryKey"`
Name string
DictionaryId string
}
type Dictionary struct {
Id string `gorm:"primaryKey"`
Name string
Records []*DictionaryRecord // 在这里使用指针
}
英文:
can you try use pointer
type DictionaryRecord struct {
Id string `gorm:"primaryKey"`
Name string
DictionaryId string
}
type Dictionary struct {
Id string `gorm:"primaryKey"`
Name string
Records []*DictionaryRecord //on this records
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论