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.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-09-12 11:00:00 +0000
Seen: 7 times
Last updated: May 31 '21