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

fix: many2many association with duplicate belongs to elem #6206

Merged
merged 1 commit into from Apr 11, 2023

Conversation

bsmith-auth0
Copy link
Contributor

  • Do only one thing
  • Non breaking API changes
  • Tested

What did this pull request do?

Extends #5473 to many2many models with belongs to associations.

User Case Description

Using the following models that have many2many and belongs to associations:

type Application struct {
	ID        string `gorm:"primarykey"`
	Name      string
	Resources []Resource 
}

type Resource struct {
	ID       string `gorm:"primarykey"`
	Name     string
	OwnerId  string
	Owner    Owner 
}

type Owner struct {
	ID   string `gorm:"primarykey"`
	Name string
}

In cases where two resources share the same Owner, attempting to update an Application using FullSaveAssociations: true will result in an error. GORM tries to insert the same Owner multiple times in a single INSERT command:

INSERT INTO "owner" ("id","name") VALUES ('1','owner-1'),('1','owner-1') ON CONFLICT ("id") DO UPDATE SET "name"="excluded"."name"
ERROR: ON CONFLICT DO UPDATE command cannot affect row a second time (SQLSTATE 21000)

After the fix, GORM will identify and insert only the unique owner(s):

INSERT INTO "owner" ("id","name") VALUES ('1','owner-1') ON CONFLICT ("id") DO UPDATE SET "name"="excluded"."name"

@jinzhu jinzhu merged commit ccc3cb7 into go-gorm:master Apr 11, 2023
24 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants