Skip to content

Creating multiple objects referencing a shared object results in that object getting created multiple times #7365

@NeariX67

Description

@NeariX67

GORM Playground Link

go-gorm/playground#788

Description

I use the terms from the playground to explain this:

Multiple users have the same manager.

manager := &user{
	name: "manager",
}
user1 := user{
	Name: "jinzhu1",
	Manager: manager,
}
user2 := user{
	Name: "jinzhu2",
	Manager: manager,
}
user3 := user{
	Name: "jinzhu3",
	Manager: manager,
}

Since all users have the same manager, the manager only needs to be created once and referenced via its ID in users 1-3. However, this does not work as expected when using

func (x *user) BeforeCreate(tx *gorm.DB) error {
	if x.ID == 0 {
		x.ID = uint(rand.Uint32())
	}

	return nil
}

The manager is assigned an ID based on BeforeCreate and gorm creates it with the same ID for every user (3 times).
This is not a problem for MariaDB or Postgres, as they simply ignore the superfluous, identical users. For MS SQL (sqlserver), however, it is a problem as it refuses to create multiple tuples with the same ID and therefore rejects all three users (no rows are inserted).
As the manager is not created but referenced in the next SQL statement (creation of users 1-3), an error occurs as the referenced manager is missing.

Expected behavior:
Gorm should create a SQL statement to insert only one manager.

Actual behavior:
Gorm creates a sql statement to insert a manager for each user, even if it is the same for each user.

Additional information

Database: MSSQL
Go version: 1.23.3

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions