Fix Preload with nil pointer

This commit is contained in:
Jinzhu 2021-04-15 10:37:05 +08:00
parent 74e7a9ca07
commit d483ffa45c
3 changed files with 4 additions and 3 deletions

View File

@ -110,7 +110,6 @@ func (p *processor) Execute(db *DB) {
for stmt.ReflectValue.Kind() == reflect.Ptr { for stmt.ReflectValue.Kind() == reflect.Ptr {
if stmt.ReflectValue.IsNil() && stmt.ReflectValue.CanAddr() { if stmt.ReflectValue.IsNil() && stmt.ReflectValue.CanAddr() {
stmt.ReflectValue.Set(reflect.New(stmt.ReflectValue.Type().Elem())) stmt.ReflectValue.Set(reflect.New(stmt.ReflectValue.Type().Elem()))
break
} }
stmt.ReflectValue = stmt.ReflectValue.Elem() stmt.ReflectValue = stmt.ReflectValue.Elem()

View File

@ -27,7 +27,6 @@ func preload(db *gorm.DB, rel *schema.Relationship, conds []interface{}, preload
}) })
if rel.JoinTable != nil { if rel.JoinTable != nil {
var ( var (
joinForeignFields = make([]*schema.Field, 0, len(rel.References)) joinForeignFields = make([]*schema.Field, 0, len(rel.References))
joinRelForeignFields = make([]*schema.Field, 0, len(rel.References)) joinRelForeignFields = make([]*schema.Field, 0, len(rel.References))

View File

@ -63,12 +63,15 @@ func TestNestedPreload(t *testing.T) {
var user2 User var user2 User
DB.Preload("Pets.Toy").Find(&user2, "id = ?", user.ID) DB.Preload("Pets.Toy").Find(&user2, "id = ?", user.ID)
CheckUser(t, user2, user) CheckUser(t, user2, user)
var user3 User var user3 User
DB.Preload(clause.Associations+"."+clause.Associations).Find(&user3, "id = ?", user.ID) DB.Preload(clause.Associations+"."+clause.Associations).Find(&user3, "id = ?", user.ID)
CheckUser(t, user3, user) CheckUser(t, user3, user)
var user4 *User
DB.Preload("Pets.Toy").Find(&user4, "id = ?", user.ID)
CheckUser(t, *user4, user)
} }
func TestNestedPreloadForSlice(t *testing.T) { func TestNestedPreloadForSlice(t *testing.T) {