diff --git a/model.go b/model.go index e1865433..abe72af9 100644 --- a/model.go +++ b/model.go @@ -35,7 +35,12 @@ func (m *Model) PrimaryKeyValue() int64 { return 0 default: result := reflect.ValueOf(m.Data).Elem() - return result.FieldByName(m.PrimaryKey()).Interface().(int64) + value := result.FieldByName(m.PrimaryKey()) + if value.IsValid() { + return result.FieldByName(m.PrimaryKey()).Interface().(int64) + } else { + return 0 + } } } diff --git a/orm.go b/orm.go index 26b4d268..39e6959c 100644 --- a/orm.go +++ b/orm.go @@ -128,8 +128,8 @@ func (s *Orm) Find(out interface{}) *Orm { } func (s *Orm) Pluck(column string, value interface{}) (orm *Orm) { - s.explain(s.model, "Query").query(value) - return + s.Select(column).explain(s.model.Data, "Query").pluck(value) + return s } func (s *Orm) Or(querystring interface{}, args ...interface{}) *Orm { diff --git a/orm_test.go b/orm_test.go index aa98db06..e6570700 100644 --- a/orm_test.go +++ b/orm_test.go @@ -226,6 +226,7 @@ func TestComplexWhere(t *testing.T) { } func TestOrder(t *testing.T) { - // var ages []int64 - // db.Model(&User).Order("age desc").Pluck("age", &ages) + var ages []int64 + db.Model(&[]User{}).Order("age desc").Pluck("age", &ages) + debug(ages) } diff --git a/sql.go b/sql.go index bd8a7dea..87b4c25f 100644 --- a/sql.go +++ b/sql.go @@ -9,6 +9,7 @@ import ( func (s *Orm) explain(value interface{}, operation string) *Orm { s.Model(value) + switch operation { case "Create": s.createSql(value) @@ -43,6 +44,7 @@ func (s *Orm) query(out interface{}) { rows, err := s.db.Query(s.Sql, s.SqlVars...) defer rows.Close() + s.Error = err if rows.Err() != nil { s.Error = rows.Err() @@ -75,6 +77,22 @@ func (s *Orm) query(out interface{}) { } } +func (s *Orm) pluck(value interface{}) { + dest_out := reflect.Indirect(reflect.ValueOf(value)) + dest_type := dest_out.Type().Elem() + + rows, err := s.db.Query(s.Sql, s.SqlVars...) + s.Error = err + + defer rows.Close() + for rows.Next() { + dest := reflect.New(dest_type).Elem() + s.Error = rows.Scan(dest) + dest_out.Set(reflect.Append(dest_out, dest)) + } + return +} + func (s *Orm) createSql(value interface{}) { columns, values := s.model.ColumnsAndValues()