Ask Your Question
1

How do I establish a foreign key with a "has one" relationship in GO using Gin, Gorm, and PostgreSQL?

asked 2021-05-22 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2021-10-31 22:00:00 +0000

plato gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2021-05-22 11:00:00 +0000

Seen: 10 times

Last updated: Oct 31 '21