To establish a foreign key with a "has one" relationship in GO using Gin, Gorm, and PostgreSQL, follow these steps:
type User struct {
ID uint `gorm:"primary_key" json:"id"`
Username string `gorm:"unique" json:"username"`
Email string `gorm:"unique" json:"email"`
...
}
type Profile struct {
ID uint `gorm:"primary_key" json:"id"`
UserID uint `gorm:"unique_index" json:"user_id"`
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
...
}
db.AutoMigrate(&Profile{})
db.Model(&Profile{}).AddForeignKey("user_id", "users(id)", "CASCADE", "CASCADE")
type User struct {
ID uint `gorm:"primary_key" json:"id"`
Username string `gorm:"unique" json:"username"`
Email string `gorm:"unique" json:"email"`
Profile Profile `gorm:"foreignKey:UserID"`
...
}
var user User
db.Preload("Profile").First(&user, id)
This will return the user with their related profile data preloaded.
Note: The foreign key constraint ensures that a Profile record can only be created if the referenced User record exists. If a User record is deleted, all related Profile records will be deleted as well, thanks to the CASCADE option we set on the foreign key constraint.
Asked: 2021-05-22 11:00:00 +0000
Seen: 11 times
Last updated: Oct 31 '21