LeTadas
LeTadas

Reputation: 3556

GO GORM foreign key constraint is not created

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.

Upvotes: 0

Views: 1674

Answers (2)

LeTadas
LeTadas

Reputation: 3556

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

Upvotes: 2

Akinwale
Akinwale

Reputation: 219

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

Upvotes: 0

Related Questions