Retrieving many-to-many results from GORM

Viewed 5640

I am mapping my database using gorm.

I have two tables (service and resource) with a many-to-many relationship. I am modelling them in code as such:

type Service struct {
    BaseModel
    Name      string     `gorm:"not null;unique_index"`
    Resources []Resource `gorm:"many2many:service_resource"`
}

type Resource struct {
    BaseModel
    Name string `gorm:"not null;unique_index"`
}

Using gorm's AutoMigrate the following tables are created:

Database diagram m2m

(I also executed a raw SQL query to add the id primary key in the mapping table.)

To create a new service, I use the following code:

service := Service{
    Name: "core",
    Resources: []Resource{
        {Name: "ec2"},
        {Name: "dynamo"},
    },
}
db.Create(&service)

This creates all the resources along with the service and fills in the relationship between them in the service_resource table just fine, as expected.

However, my problem is when I'm querying for the services. I use the following code to retrieve all services:

services := []model.Service{}
db.Find(&services)

This returns successfully with the services array populated, but the Resources array of each service is empty:

"services": [
    {
        "ID": 1,
        "Name": "core",
        "Resources": null
    },
    ...
]

I was under the assumption that gorm would populate it automatically. Is there some step that I'm missing?

1 Answers
Related