Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Duplicate entry when creating an entity in many2many relationship #7019

Open
nickbel7 opened this issue May 15, 2024 · 1 comment
Open

Duplicate entry when creating an entity in many2many relationship #7019

nickbel7 opened this issue May 15, 2024 · 1 comment
Assignees
Labels

Comments

@nickbel7
Copy link

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
}
@github-actions github-actions bot added the type:missing reproduction steps missing reproduction steps label May 15, 2024
Copy link

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.ioSearch Before Asking

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants