2

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 Answer 1

1

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")
Sign up to request clarification or add additional context in comments.

1 Comment

Forgot to mention, but myStruct is also the model for my database table, the only single at the moment. From your reply, I suppose I have to make other separate table(s) to house record about individual videos, then draw a one-to-many relationship with my current single table?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.