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.
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: 2021-05-22 11:00:00 +0000
Seen: 10 times
Last updated: Oct 31 '21
How can the SQL debug mode be activated in PostgreSQL version 15.2?
What is the procedure for using pg_restore on Windows with Docker?
What is the equivalent of SQL Server NVARCHAR in PostgreSQL?
What is the method to retrieve the JSON data from a column in SQL?
How to solve the issue of being unable to establish a connection with libpq on Mac M1?
Is it possible to launch multiple instances of PostgreSQL using Spring Boot Testcontainers?
Due to SyntaxError, why am I unable to create a TIMESTAMP WITH TIMEZONE column in postgres?