How to work with has many relation in gorm?

Viewed 147
import (
    "gorm.io/gorm"
    "gorm.io/driver/postgres"
)

type School struct {
    gorm.Model
    Students        []Student      `json:"students"`
}

type Student struct {
    gorm.Model
    Name            string         `json:"name"`
}

func init() {
    //connect to db first
    conn, err := gorm.Open(postgres.New(postgres.Config{
        DSN:                  dbUri,
        PreferSimpleProtocol: true,
    }), &gorm.Config{})
    if err != nil {
        log.Fatal(err)
    }

    db = conn
    db.AutoMigrate(&Student{}, &School{})
}

Create the structs and automigrating it gives me an error. Do you know why this is? Also how to you work with has many relation in gorm, what kind of data does it create in postgres?

Error - Need to define a valid foreign key for relations or it need to implement the Valuer/Scanner interface

1 Answers

You need to add a SchoolID field to your Student. See the docs here for full usage.

type Student struct {
    gorm.Model
    SchoolID        uint
    Name            string         `json:"name"`
}

To answer the second part, it will create two tables for you. Schools and students. The students will have a foreign key that points to the ID of a school. I would read the docs to learn how this works more.

Related