One to many relationship with gorm in golang doesnt work

4.3k Views Asked by At

I have two tables:

type Person struct {
    ID int
    FirstName string
    LastName string
    Functions []Function
}

type Function struct {
    gorm.Model
    Info string
    Person Person
}

I create the tables like this:

db.AutoMigrate(&models.Person{}, &models.Function{})

I then initialize the database:

user := models.Person{
    FirstName: "Isa",
    LastName:  "istcool",
    Functions: []models.Function{{Info: "Trainer"}, {Info: "CEO"}},
}
db.Create(&user)

Now the problem is that my Person table only got Firstname and Lastname columns and my Function table only got the Info column. But when I start my GET request I get people with the column function which is always null.

Here is a screenshot from my GET request and my db

To see the code visit my GitHub repo

1

There are 1 best solutions below

0
On BEST ANSWER

Finally found the answer!! The problem is my GET functions I have to use

db.Preload("Functions").Find(&[]models.Person{})

instead of

db.Find(&[]models.Person{})