Handle Associations with pointer of pointer, close #3130

This commit is contained in:
Jinzhu 2020-07-10 22:53:03 +08:00
parent d4b462a351
commit 1f05cb7e55
2 changed files with 8 additions and 2 deletions

View File

@ -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
}

View File

@ -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)