Fix scan with interface

This commit is contained in:
Jinzhu 2021-09-17 18:35:14 +08:00
parent da16a8aac6
commit ab355336cb
2 changed files with 12 additions and 2 deletions

View File

@ -190,11 +190,13 @@ func Scan(rows *sql.Rows, db *DB, initialized bool) {
}
if isPtr {
db.Statement.ReflectValue.Set(reflect.Append(reflectValue, elem))
reflectValue = reflect.Append(reflectValue, elem)
} else {
db.Statement.ReflectValue.Set(reflect.Append(reflectValue, elem.Elem()))
reflectValue = reflect.Append(reflectValue, elem.Elem())
}
}
db.Statement.ReflectValue.Set(reflectValue)
case reflect.Struct, reflect.Ptr:
if reflectValue.Type() != Schema.ModelType {
Schema, _ = schema.Parse(db.Statement.Dest, db.cacheStore, db.NamingStrategy)

View File

@ -103,6 +103,14 @@ func TestScan(t *testing.T) {
} else if rus := resInt4.([]User); len(rus) == 0 || rus[0].ID != user3.ID || rus[0].Name != user3.Name || rus[0].Age != user3.Age {
t.Fatalf("Scan into struct should work, got %#v, should %#v", resInt4, user3)
}
var resInt5 interface{}
resInt5 = []User{}
if err := DB.Table("users").Select("id, name, age").Where("id IN ?", []uint{user1.ID, user2.ID, user3.ID}).Find(&resInt5).Error; err != nil {
t.Fatalf("Failed to query with pointer of value, got error %v", err)
} else if rus := resInt5.([]User); len(rus) != 3 {
t.Fatalf("Scan into struct should work, got %+v, len %v", resInt5, len(rus))
}
}
func TestScanRows(t *testing.T) {