From 1f05cb7e55ece75a08ae79fc1c867ae023ade8c6 Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Fri, 10 Jul 2020 22:53:03 +0800 Subject: [PATCH] Handle Associations with pointer of pointer, close #3130 --- association.go | 5 ++++- tests/associations_belongs_to_test.go | 5 ++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/association.go b/association.go index eeb11efe..516a8c57 100644 --- a/association.go +++ b/association.go @@ -30,7 +30,10 @@ func (db *DB) Association(column string) *Association { association.Error = fmt.Errorf("%w: %v", ErrUnsupportedRelation, column) } - db.Statement.ReflectValue = reflect.Indirect(reflect.ValueOf(db.Statement.Model)) + db.Statement.ReflectValue = reflect.ValueOf(db.Statement.Model) + for db.Statement.ReflectValue.Kind() == reflect.Ptr { + db.Statement.ReflectValue = db.Statement.ReflectValue.Elem() + } } else { association.Error = err } diff --git a/tests/associations_belongs_to_test.go b/tests/associations_belongs_to_test.go index 1800be91..3e4de726 100644 --- a/tests/associations_belongs_to_test.go +++ b/tests/associations_belongs_to_test.go @@ -18,7 +18,10 @@ func TestBelongsToAssociation(t *testing.T) { // Find var user2 User DB.Find(&user2, "id = ?", user.ID) - DB.Model(&user2).Association("Company").Find(&user2.Company) + pointerOfUser := &user2 + if err := DB.Model(&pointerOfUser).Association("Company").Find(&user2.Company); err != nil { + t.Errorf("failed to query users, got error %#v", err) + } user2.Manager = &User{} DB.Model(&user2).Association("Manager").Find(user2.Manager) CheckUser(t, user2, user)