diff --git a/callbacks/associations.go b/callbacks/associations.go index 10819dcc..2a4efbe1 100644 --- a/callbacks/associations.go +++ b/callbacks/associations.go @@ -377,7 +377,7 @@ func saveAssociations(db *gorm.DB, rel *schema.Relationship, values interface{}, if len(selects) > 0 { tx = tx.Select(selects) - } else if len(selectColumns) > 0 && len(omits) == 0 { + } else if restricted && len(omits) == 0 { tx = tx.Omit(clause.Associations) } diff --git a/schema/relationship_test.go b/schema/relationship_test.go index a34777b7..2971698c 100644 --- a/schema/relationship_test.go +++ b/schema/relationship_test.go @@ -398,6 +398,31 @@ func TestMultipleMany2Many(t *testing.T) { ) } +func TestSelfReferentialMany2Many(t *testing.T) { + type User struct { + ID int32 `gorm:"primaryKey"` + Name string + CreatedBy int32 + Creators []User `gorm:"foreignKey:CreatedBy"` + AnotherPro interface{} `gorm:"-"` + } + + checkStructRelation(t, &User{}, Relation{ + Name: "Creators", Type: schema.HasMany, Schema: "User", FieldSchema: "User", + References: []Reference{{"ID", "User", "CreatedBy", "User", "", true}}, + }) + + user, err := schema.Parse(&User{}, &sync.Map{}, schema.NamingStrategy{}) + if err != nil { + t.Fatalf("failed to parse schema") + } + + relSchema := user.Relationships.Relations["Creators"].FieldSchema + if user != relSchema { + t.Fatalf("schema should be same, expects %p but got %p", user, relSchema) + } +} + type CreatedByModel struct { CreatedByID uint CreatedBy *CreatedUser