Mike Abbey
Mike Abbey

Reputation: 173

Insert Array of Structs into DB using gorm

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?

Upvotes: 2

Views: 2696

Answers (1)

Eddwin Paz
Eddwin Paz

Reputation: 2878

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")

Upvotes: 1

Related Questions