Search code examples
gogo-gorm

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.


Solution

  • 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