Skip to content

Commit 220349c

Browse files
committed
Fix omit associations, close go-gorm#4161
1 parent e85b73e commit 220349c

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

callbacks/associations.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,7 +377,7 @@ func saveAssociations(db *gorm.DB, rel *schema.Relationship, values interface{},
377377

378378
if len(selects) > 0 {
379379
tx = tx.Select(selects)
380-
} else if len(selectColumns) > 0 && len(omits) == 0 {
380+
} else if restricted && len(omits) == 0 {
381381
tx = tx.Omit(clause.Associations)
382382
}
383383

schema/relationship_test.go

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,31 @@ func TestMultipleMany2Many(t *testing.T) {
398398
)
399399
}
400400

401+
func TestSelfReferentialMany2Many(t *testing.T) {
402+
type User struct {
403+
ID int32 `gorm:"primaryKey"`
404+
Name string
405+
CreatedBy int32
406+
Creators []User `gorm:"foreignKey:CreatedBy"`
407+
AnotherPro interface{} `gorm:"-"`
408+
}
409+
410+
checkStructRelation(t, &User{}, Relation{
411+
Name: "Creators", Type: schema.HasMany, Schema: "User", FieldSchema: "User",
412+
References: []Reference{{"ID", "User", "CreatedBy", "User", "", true}},
413+
})
414+
415+
user, err := schema.Parse(&User{}, &sync.Map{}, schema.NamingStrategy{})
416+
if err != nil {
417+
t.Fatalf("failed to parse schema")
418+
}
419+
420+
relSchema := user.Relationships.Relations["Creators"].FieldSchema
421+
if user != relSchema {
422+
t.Fatalf("schema should be same, expects %p but got %p", user, relSchema)
423+
}
424+
}
425+
401426
type CreatedByModel struct {
402427
CreatedByID uint
403428
CreatedBy *CreatedUser

0 commit comments

Comments
 (0)