pkaramol
pkaramol

Reputation: 19322

gorm not establishing foreign key relationshop in the database schema

I have the following 2 gorm models

// Day is a corresponding day entry
type Day struct {
    gorm.Model
    Dateday   string         `json:"dateday" gorm:"type:date;NOT NULL"`
    Nameday   string         `json:"nameday" gorm:"type:varchar(100);NOT NULL"`
    Something sql.NullString `json:"something"`
    Holyday   bool           `json:"holyday"`
}

type Week struct {
    gorm.Model
    Start Day
    End   Day
}

However, after performing the migrations

db.AutoMigrate(&Day{})
db.AutoMigrate(&Week{})

logging into the db and describing table weeks

postgres-# \d+ weeks;
                                                          Table "public.weeks"
   Column   |           Type           | Collation | Nullable |              Default              | Storage | Stats target | Description
------------+--------------------------+-----------+----------+-----------------------------------+---------+--------------+-------------
 id         | integer                  |           | not null | nextval('weeks_id_seq'::regclass) | plain   |              |
 created_at | timestamp with time zone |           |          |                                   | plain   |              |
 updated_at | timestamp with time zone |           |          |                                   | plain   |              |
 deleted_at | timestamp with time zone |           |          |                                   | plain   |              |
Indexes:
    "weeks_pkey" PRIMARY KEY, btree (id)
    "idx_weeks_deleted_at" btree (deleted_at)

I don't see the start / end fields, that should presumably also be Foreign Key to the day table (that does exist)

Why is that?

Upvotes: 1

Views: 174

Answers (1)

Grigoriy Mikhalkin
Grigoriy Mikhalkin

Reputation: 5573

To set one-to-one relationship you need to also add id field to struct. By default you should name it as [YourFieldName]ID, if you want to use some other name for id field, you can do it via tag (see docs for more details), for example:

type Week struct {
    gorm.Model
    Start    Day
    End      Day `gorm:"foreignkey:EndRefer"`
    StartID  uint
    EndRefer uint
}

But beware, AutoMigrate can't create foreign key constraint(here's related issue). You have to set it yourself with AddForeignKey method.

Upvotes: 2

Related Questions