db.AutoMigrate(&student.Student{})
db.AutoMigrate(&address.Address{})
db.AutoMigrate(&subject.Subject{})
user := student.Student{
Adresses: []address.Address{
{City: "mum", State: "india", Country: "jjm", Pincode: "5859"},
{City: "muk", State: "inia", Country: "ojm", Pincode: "5779"},
{City: "pum", State: "rindia", Country: "8jm", Pincode: "6159"},
{City: "rum", State: "ljndia", Country: "hjm", Pincode: "1459"},
}, Subs: []subject.Subject{
subject.Subjects[0], subject.Subjects[1], subject.Subjects[2],
},
}
我想把这个结构添加到mysql数据库中,但是当我运行更新查询时,只有数组的第一个元素在数据库中被更新,我想把所有的元素都推到那个数据库中,你能帮我吗?
用于更新的函数
func Testupdate(n int, st student.Student) {
dsn := "root:Pranav@18@tcp(127.0.0.1:3306)/students_data?charset=utf8&parseTime=True"
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
panic("failed to connect database")
}
db.AutoMigrate(&student.Student{})
db.AutoMigrate(&address.Address{})
db.AutoMigrate(&subject.Subject{})
var sd student.Student
db.First(&sd, n)
db.Model(&sd).Update("Adresses", st.Adresses)
db.Model(&sd).Update("Subs", st.Subs)
db.Save(&sd)}
1条答案
按热度按时间juzqafwq1#
使用gormv2批量添加
它有一个用于此目的的批量添加选项