mirror of https://github.com/go-gorm/gorm.git
Add Pluck
This commit is contained in:
parent
244b27a6a0
commit
334d05645f
7
model.go
7
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
|
4
orm.go
4
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 {
|
||||
|
|
|
@ -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)
|
||||
}
|
||||
|
|
18
sql.go
18
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()
|
||||
|
||||
|
|
Loading…
Reference in New Issue