测试程序如下:

package main

import (
    "fmt"
    "gorm.io/driver/sqlite"
    "gorm.io/gorm"
    "log"
    "time"
)

type Card struct {
    CardName    string  `gorm:"column:cardName;"`
    CardId      int     `gorm:"column:cardId;"`
    UserID      uint    `gorm:"index"`
}

type User struct {
    ID      uint        `gorm:"primarykey"`
    Name    string      `gorm:"column:name; type:varchar(64)"`
    Time    time.Time
    Cards   []Card
}

func main(){
    var user User
    var card Card
    db, err := gorm.Open(sqlite.Open("test.db"), &gorm.Config{})
    if err != nil {
        log.Panic(err)
    }
    _ = db.AutoMigrate(&user)
    _ = db.AutoMigrate(&card)
    ret := dataEncode(1)
    /*create data*/
    err = db.Save(&ret).Error
    if err != nil {
        log.Printf("create user error, err = %v", err)
    }
    ret = dataEncode(2)
    err = db.Create(&ret).Error
    if err != nil {
        log.Printf("create user error, err = %v", err)
    }
    /*query data*/
    err = db.Preload("Cards").Last(&user).Error
    if err != nil {
        log.Printf("query data error, err = %v", err)
    }
    log.Printf("cards len is %d", len(user.Cards))
}


func dataEncode(index int) User {
    return User{
        Name: fmt.Sprintf("name-%d", index),
        Time: time.Now(),
        Cards: []Card{
            {
                CardName: fmt.Sprintf("card%d-01", index),
                CardId: 32,
            },
            {
                CardName: fmt.Sprintf("card%d-02", index),
                CardId: 33,
            },
            {
                CardName: fmt.Sprintf("card%d-03", index),
                CardId: 34,
            },
        },
    }
}

出现问题的go.mod:

module sqlite-gorm

go 1.16

require (
    gorm.io/driver/sqlite v1.3.1
    gorm.io/gorm v1.23.1
)

我尝试使用Has Many功能,一个User关联三个Card.但是执行代码发现,Card只被写入了一个。


正常的go.mod

module sqlite-gorm

go 1.16

require (
    gorm.io/driver/sqlite v1.1.6
    gorm.io/gorm v1.21.16
)

当我回退gorm和sqlite版本之后,一个User的三个Card均被正常写入。

Comment From: github-actions[bot]

The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking