将结构体数组插入数据库使用gorm

huangapple go评论124阅读模式
英文:

Insert Array of Structs into DB using gorm

问题

我需要使用gorm将数据插入到Postgresql数据库中。但是,所涉及的结构体中包含了自定义类型的数组字段:

type VideoFile struct {
    UID      string
    FileName string
    Format   string
    Path     string
}

type myStruct struct {
    ID                string
    UserId            uint64
    UserType          int
    FaceVideoFiles    []VideoFile
    MeetingVideoFiles []VideoFile
}

func (r *videoRepo) CreateRecord(input *myStruct) error {
    tx := r.base.GetDB().Begin()
    err := tx.Create(input).Error
    if err != nil {
        tx.Rollback()
        return err
    }
    tx.Commit()
    return nil
}

在数据库中,ID字段是主键。我不确定在结构体字段中应该添加哪些标签,所以这里留空了(例如gorm:"primaryKey" json:"id"等)。如果FaceVideoFiles不是一个结构体数组,似乎一切正常,但是对于结构体数组来说情况就不同了。我应该怎么做才能将这些结构体数组(而不是单个结构体)插入到我的数据库中呢?

英文:

I need to insert into a Postgresql database using gorm. But the struct in question has fields containing arrays of custom types:

type VideoFile struct {
    UID      string
    FileName string
    Format   string
    Path     string
}


type myStruct struct {
    ID                string
	UserId            uint64
	UserType          int
	FaceVideoFiles    []VideoFile
	MeetingVideoFiles []VideoFile
}

func (r *videoRepo) CreateRecord(input *myStruct) error {
	tx := r.base.GetDB().Begin()
	err := tx.Create(input).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

ID field is the primary key in database. I am not sure which tags to add to the struct fields so I leave it empty here (e.g. gorm:"primaryKey" json:"id", etc). If the FaceVideoFiles is not an array of struct, things seem to work, but that is not the case with an array of struct. What should I do so that I can insert those arrays of structs (not individual structs) into my database?

答案1

得分: 1

你需要使用一对多关系。更多相关信息,请参考文档:https://gorm.io/docs/has_many.html#Has-Many

type Dog struct {
  ID   int
  Name string
  Toys []Toy `gorm:"polymorphic:Owner;"`
}

type Toy struct {
  ID        int
  Name      string
  OwnerID   int
  OwnerType string
}

db.Create(&Dog{Name: "dog1", Toys: []Toy{{Name: "toy1"}, {Name: "toy2"}}})
// INSERT INTO `dogs` (`name`) VALUES ("dog1")
// INSERT INTO `toys` (`name`,`owner_id`,`owner_type`) VALUES ("toy1","1","dogs"), ("toy2","1","dogs")

以上是代码的翻译部分。

英文:

You have to use one to many. More information related to this. Please follow documentation. https://gorm.io/docs/has_many.html#Has-Many

type Dog struct {
  ID   int
  Name string
  Toys []Toy `gorm:"polymorphic:Owner;"`
}

type Toy struct {
  ID        int
  Name      string
  OwnerID   int
  OwnerType string
}

db.Create(&Dog{Name: "dog1", Toys: []Toy{{Name: "toy1"}, {Name: "toy2"}}})
// INSERT INTO `dogs` (`name`) VALUES ("dog1")
// INSERT INTO `toys` (`name`,`owner_id`,`owner_type`) VALUES ("toy1","1","dogs"), ("toy2","1","dogs")

huangapple
  • 本文由 发表于 2022年7月28日 12:21:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/73147245.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定