Ask Your Question

Revision history [back]

The method to direct foreign key from a child to its parent in GORM is to use the belongsTo relationship. This relationship maps a child to its parent and creates a foreign key column in the child's table pointing to the parent's primary key.

Example:

type Parent struct {
    ID     uint
    Name   string
    Childs []Child
}

type Child struct {
    ID       uint
    Name     string
    ParentID uint
    Parent   Parent `gorm:"foreignkey:ParentID"`
}

In the above example, the Child struct has a foreign key ParentID pointing to the ID field in the Parent struct. The Parent field in the Child struct is annotated with gorm:"foreignkey:ParentID" to specify the foreign key column name. The Parent field is of type Parent, and it represents the parent object associated with the child object.

To create a Child object and associate it with a Parent object, you can use the following code:

parent := Parent{Name: "John"}
child := Child{Name: "Jane", Parent: parent}

db.Create(&parent)
db.Create(&child)

This will create a new Parent record and a new Child record with the ParentID foreign key set to the ID of the Parent record.