retrieving gorm object support pointer

This commit is contained in:
rorschach 2021-01-26 20:08:41 +08:00 committed by Jinzhu
parent f6308ed223
commit ba59065024
3 changed files with 12 additions and 1 deletions

View File

@ -94,6 +94,11 @@ func (p *processor) Execute(db *DB) {
if stmt.Dest != nil {
stmt.ReflectValue = reflect.ValueOf(stmt.Dest)
for stmt.ReflectValue.Kind() == reflect.Ptr {
if stmt.ReflectValue.IsNil() {
stmt.ReflectValue.Set(reflect.New(stmt.ReflectValue.Type().Elem()))
break
}
stmt.ReflectValue = stmt.ReflectValue.Elem()
}
if !stmt.ReflectValue.IsValid() {

View File

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

View File

@ -28,6 +28,12 @@ func TestScan(t *testing.T) {
t.Fatalf("Scan into struct should work, got %#v, should %#v", res, user3)
}
var resPointer *result
DB.Table("users").Select("id, name, age").Where("id = ?", user3.ID).Scan(&resPointer)
if res.ID != user3.ID || res.Name != user3.Name || res.Age != int(user3.Age) {
t.Fatalf("Scan into struct should work, got %#v, should %#v", res, user3)
}
DB.Table("users").Select("id, name, age").Where("id = ?", user2.ID).Scan(&res)
if res.ID != user2.ID || res.Name != user2.Name || res.Age != int(user2.Age) {
t.Fatalf("Scan into struct should work, got %#v, should %#v", res, user2)