Your Question
I have 2 structs: Aa struct has many B structs.
I want to create multiple B records by using association mode create.
It works fine with gorm.io/driver/mysql v1.2.0 and gorm.io/gorm v1.22.3.
However, with gorm.io/driver/mysql v1.3.5 and gorm.io/gorm v1.23.8, it will create only one B record.
The following is my code snippet.
package main
import (
"fmt"
"log"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
type Aa struct {
AID string `gorm:"primaryKey"`
Bs []B `gorm:"foreignKey:AID;references:AID"`
}
type B struct {
AID string `gorm:"index"`
BID string
}
func initDB(dbHost, dbName, dbPort, dbUser, dbPassword string) (*gorm.DB, error) {
// connect to db
dsn := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", dbUser, dbPassword, dbHost, dbPort, dbName)
db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{DryRun: true})
if err != nil {
return nil, fmt.Errorf("failed to open DB with DSN %s: %v", dsn, err)
}
return db, nil
}
func main() {
db, err := initDB("localhost", "test", "3306", "root", "")
if err != nil {
log.Fatalf("failed to init db: %v", err)
}
bs := []B{
{
AID: "aid",
BID: "bid1",
},
{
AID: "aid",
BID: "bid2",
},
}
a := Aa{
AID: "aid",
Bs: bs,
}
if err := db.Create(a).Error; err != nil {
log.Fatalf("failed to create records: %v", err)
}
}
The document you expected this should be explained
https://gorm.io/docs/associations.html#Auto-Create-x2F-Update
Expected answer
I suppose it would create multiple B records for me
Comment From: github-actions[bot]
This issue has been automatically marked as stale because it has been open 360 days with no activity. Remove stale label or comment or this will be closed in 180 days