Description
I want to create a many2many relationship between a user and a house. 1. I create the following entities (the tables are created correctly) through the 'AutoMigrate' method 2. Then I go and create a House entity 3. Then I create a User entity and I reference the uuid of the previously created house.
PROBLEM: the user that gets created is not linked to the existing house through the link table('user_houses'). Instead, a new house entry is created with a new uuid, which then gets linked to the user.
Below I share the declaration of the entities hoping someone has struck on the same issue!
type UsersTable struct {
ID uuid.UUID `gorm:"type:uuid;primaryKey"`
Username string `json:"username" gorm:"not null"`
Password string `json:"password" gorm:"not null"`
Email string `json:"email"`
Houses []*HousesTable `gorm:"many2many:user_houses;"`
}
type HousesTable struct {
ID uuid.UUID `gorm:"type:uuid;primaryKey"`
Name string `json:"name" gorm:"not null"`
Address string `json:"address"`
Users []*UsersTable `gorm:"many2many:user_houses;"`
}
func (u *UsersTable) BeforeCreate(tx *gorm.DB) (err error) {
u.ID = uuid.New()
return
}
func (u *HousesTable) BeforeCreate(tx *gorm.DB) (err error) {
u.ID = uuid.New()
return
}
Comment From: github-actions[bot]
The issue has been automatically marked as stale as it missing playground pull request link, which is important to help others understand your issue effectively and make sure the issue hasn't been fixed on latest master, checkout https://github.com/go-gorm/playground for details. it will be closed in 30 days if no further activity occurs. if you are asking question, please use the Question template, most likely your question already answered https://github.com/go-gorm/gorm/issues or described in the document https://gorm.io ✨ Search Before Asking ✨