One-to-many relation need to define a valid foreign key error

Viewed 1069

I want to make a webapp and I have a simple data model with a one to many relation. I tried sticking to the documentation of gorm and from my understanding this should work:

package dbModels

import "gorm.io/gorm"

type Post struct {
    gorm.Model
    Text string
    Likes int
    Comments []Comment 
}

type Comment struct {
    gorm.Model
    Text string
    Likes int
    PostID uint
}

I'm migrating these models like that:

db.AutoMigrate(&dbModels.Post{}, &dbModels.Comment{})

Then I want to put this object in post:

func (r *mutationResolver) CreatePost(ctx context.Context, input model.PostInput) (*model.Post, error) {
    var items []*model.Comment
    post := model.Post{
        Text:     input.Text,
        Likes:    0,
        Comments: items,
    }
    r.DB.Create(&post)
    return &post, nil
}

however I get the following error:

2021/01/31 11:23:01 /home/felix/Projekte/GoReact/server/graph/schema.resolvers.go:21 invalid field found for struct github.com/blamefelix/TwitterClone/graph/model.Post's field Comments, need to define a valid foreign key for relations or it need to implement the Valuer/Scanner interface

I don't really understand what I'm doing wrong. From the gorm documentation I thought the relation would get managed by gorm if I put it like that? My suspicion is, that I put the wrong data in?

1 Answers

So I've managed to fix it by using the same model for graphql and gorm. The problem must have been that I've pased the wrong data into the db create function

Related