mirror of https://github.com/go-gorm/gorm.git
yay, find from db works
This commit is contained in:
parent
0b1facc513
commit
69f53a4b41
14
orm.go
14
orm.go
|
@ -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
|
||||
}
|
||||
|
||||
|
|
|
@ -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")
|
||||
}
|
||||
|
|
2
utils.go
2
utils.go
|
@ -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())
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue