yay, find from db works

This commit is contained in:
Jinzhu 2013-10-26 11:48:07 +08:00
parent 0b1facc513
commit 69f53a4b41
3 changed files with 17 additions and 2 deletions

14
orm.go
View File

@ -2,6 +2,8 @@ package gorm
import (
"errors"
"fmt"
"reflect"
"strconv"
@ -115,6 +117,18 @@ func (s *Orm) Exec(sql ...string) *Orm {
func (s *Orm) First(out interface{}) *Orm {
s.setModel(out)
rows, err := s.db.Query("SELECT * from users limit 1")
s.Error = err
for rows.Next() {
dest := reflect.ValueOf(out).Elem()
fmt.Printf("%+v", dest)
columns, _ := rows.Columns()
var values []interface{}
for _, value := range columns {
values = append(values, dest.FieldByName(value).Addr().Interface())
}
s.Error = rows.Scan(values...)
}
return s
}

View File

@ -16,12 +16,13 @@ func getDB() DB {
}
func TestSaveAndFirst(t *testing.T) {
// create table "users" ("name" varchar(255));
db := getDB()
u := &User{Name: "jinzhu"}
db.Save(u)
user := &User{}
db.First(&user)
db.First(user)
if user.Name != "jinzhu" {
t.Errorf("User should be saved and fetched correctly")
}

View File

@ -12,7 +12,7 @@ func modelValues(m interface{}) (columns []string, values []interface{}) {
for i := 0; i < typ.NumField(); i++ {
p := typ.Field(i)
if !p.Anonymous {
columns = append(columns, strings.ToLower(p.Name))
columns = append(columns, p.Name)
value := reflect.ValueOf(m).Elem().FieldByName(p.Name)
values = append(values, value.Interface())
}