Fix Pluck with Table only

This commit is contained in:
Jinzhu 2020-06-09 15:34:55 +08:00
parent 05e6a65ee1
commit 22ff8377df
3 changed files with 27 additions and 25 deletions

View File

@ -289,16 +289,16 @@ func (db *DB) Pluck(column string, dest interface{}) (tx *DB) {
column = f.DBName
}
}
tx.Statement.AddClauseIfNotExists(clause.Select{
Distinct: tx.Statement.Distinct,
Columns: []clause.Column{{Name: column}},
})
tx.Statement.Dest = dest
tx.callbacks.Query().Execute(tx)
} else {
} else if tx.Statement.Table == "" {
tx.AddError(ErrorModelValueRequired)
}
tx.Statement.AddClauseIfNotExists(clause.Select{
Distinct: tx.Statement.Distinct,
Columns: []clause.Column{{Name: column}},
})
tx.Statement.Dest = dest
tx.callbacks.Query().Execute(tx)
return
}

34
scan.go
View File

@ -84,24 +84,26 @@ func Scan(rows *sql.Rows, db *DB, initialized bool) {
db.Statement.ReflectValue.Set(reflect.MakeSlice(db.Statement.ReflectValue.Type(), 0, 0))
for idx, column := range columns {
if field := db.Statement.Schema.LookUpField(column); field != nil && field.Readable {
fields[idx] = field
} else if names := strings.Split(column, "__"); len(names) > 1 {
if len(joinFields) == 0 {
joinFields = make([][2]*schema.Field, len(columns))
}
if rel, ok := db.Statement.Schema.Relationships.Relations[names[0]]; ok {
if field := rel.FieldSchema.LookUpField(strings.Join(names[1:], "__")); field != nil && field.Readable {
fields[idx] = field
joinFields[idx] = [2]*schema.Field{rel.Field, field}
continue
if db.Statement.Schema != nil {
for idx, column := range columns {
if field := db.Statement.Schema.LookUpField(column); field != nil && field.Readable {
fields[idx] = field
} else if names := strings.Split(column, "__"); len(names) > 1 {
if len(joinFields) == 0 {
joinFields = make([][2]*schema.Field, len(columns))
}
if rel, ok := db.Statement.Schema.Relationships.Relations[names[0]]; ok {
if field := rel.FieldSchema.LookUpField(strings.Join(names[1:], "__")); field != nil && field.Readable {
fields[idx] = field
joinFields[idx] = [2]*schema.Field{rel.Field, field}
continue
}
}
values[idx] = &sql.RawBytes{}
} else {
values[idx] = &sql.RawBytes{}
}
values[idx] = &sql.RawBytes{}
} else {
values[idx] = &sql.RawBytes{}
}
}

View File

@ -21,7 +21,7 @@ func TestDistinct(t *testing.T) {
}
var names []string
DB.Model(&User{}).Where("name like ?", "distinct%").Order("name").Pluck("Name", &names)
DB.Table("users").Where("name like ?", "distinct%").Order("name").Pluck("name", &names)
AssertEqual(t, names, []string{"distinct", "distinct", "distinct", "distinct-2", "distinct-3"})
var names1 []string