How do I seed data to Postgresql using GORM

Viewed 130

Overview

I've just started learning golang and using GORM as the ORM but I can't seem to find documentation or how to create seed data and how to seed it. Hopefully someone here could help me with that

I have tried following this step by Ilija Eftimov but it doesn't work or I don't know where I did wrong. Basically the function seed.Seed needs a return data which is error but the code he made doesn't have that.

Environment

  • OS=Ubuntu 20.04.4 (Windows 11 | WSL 2)
  • Go=1.18.3
  • IDE=VSCode
  • ORM=GORM `github.com/jinzhu/gorm v1.9.16

Files

models/users.go
type User struct {
    gorm.Model

    Email    string `gorm:"typevarchar(100);unique_index;not null"`
    Password string `json:"-"`
    UserType string
    Players  []Player
}
models/players.go
type Player struct {
    gorm.Model

    FirstName       string `gorm:"not null"`
    LastName        string
    Gender          string
    PrimaryPosition string
    Email           string
    UserID          int
    Team            string
}

Expected response

I do hope there's either a github package that help us handle seed file and seeding it or a way to seed using GORM. From what I understand for now, we need to create seed files in:

  • pkg\seed for main seed function
  • pkg\seeds for users and players seed data
0 Answers
Related