我如何使用GORM将整个数组的结构添加到mysql数据库中

iswrvxsc  于 2022-12-07  发布在  Go
关注(0)|答案(1)|浏览(275)
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)}
juzqafwq

juzqafwq1#

使用gormv2批量添加
它有一个用于此目的的批量添加选项

相关问题