Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

To establish a foreign key with a "has one" relationship in GO using Gin, Gorm, and PostgreSQL, follow these steps:

  1. Create the primary table with a unique identifier column. This table will have the "one" side of the relationship.
type User struct {
    ID        uint   `gorm:"primary_key" json:"id"`
    Username  string `gorm:"unique" json:"username"`
    Email     string `gorm:"unique" json:"email"`
    ...
}
  1. Create the related table with a foreign key column. This table will have the "has one" side of the relationship.
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"`
    ...
}
  1. Set up the foreign key constraint in the related table's migration. This will ensure that the UserID column in the Profile table references the ID column in the User table.
db.AutoMigrate(&Profile{})
db.Model(&Profile{}).AddForeignKey("user_id", "users(id)", "CASCADE", "CASCADE")
  1. Define the relationship in the User model.
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"`
    ...
}
  1. Preload the related data when querying the primary table.
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.