0

I'm having issues with creating foreign key constraint for the Belongs to relationship.

A struct containing foreign key:

type Summary struct { Id string `gorm:"primaryKey"` OwnerId *string `gorm:"foreignKey:OwnerId references:Id;not null"` Title string } 

Struct to which summary belongs to:

type Owner struct { Id string `gorm:"primaryKey"` Name string } 

It creates the tables in SQL without a problem but SQL schema doesn't contain foreign key constraint in the summary table on the owner_id column and therefore Summary can be inserted when an owner doesn't exist.

0

2 Answers 2

2

What eventually worked but not the perfect solution in my opinion is referencing the Owner struct inside Summary like so:

type Summary struct { Id string `gorm:"primaryKey"` OwnerId string Owner Owner `gorm:"foreignKey:OwnerId"` Title string } 

I wonder if it's the only way to do so

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, that's what you need to do, according to the docs gorm belongsTo
0

What version of gorm are you using? If you are on v1 of the library, try switching to v2. I experienced similar issues while using v1 of the library.

v1 dependency download

go get -u github.com/jinzhu/gorm 

v2 dependency download

go get -u gorm.io/gorm 

1 Comment

I use the latest one gorm.io/gorm v1.21.7

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.