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,6 +289,9 @@ func (db *DB) Pluck(column string, dest interface{}) (tx *DB) {
column = f.DBName column = f.DBName
} }
} }
} else if tx.Statement.Table == "" {
tx.AddError(ErrorModelValueRequired)
}
tx.Statement.AddClauseIfNotExists(clause.Select{ tx.Statement.AddClauseIfNotExists(clause.Select{
Distinct: tx.Statement.Distinct, Distinct: tx.Statement.Distinct,
@ -296,9 +299,6 @@ func (db *DB) Pluck(column string, dest interface{}) (tx *DB) {
}) })
tx.Statement.Dest = dest tx.Statement.Dest = dest
tx.callbacks.Query().Execute(tx) tx.callbacks.Query().Execute(tx)
} else {
tx.AddError(ErrorModelValueRequired)
}
return return
} }

View File

@ -84,6 +84,7 @@ func Scan(rows *sql.Rows, db *DB, initialized bool) {
db.Statement.ReflectValue.Set(reflect.MakeSlice(db.Statement.ReflectValue.Type(), 0, 0)) db.Statement.ReflectValue.Set(reflect.MakeSlice(db.Statement.ReflectValue.Type(), 0, 0))
if db.Statement.Schema != nil {
for idx, column := range columns { for idx, column := range columns {
if field := db.Statement.Schema.LookUpField(column); field != nil && field.Readable { if field := db.Statement.Schema.LookUpField(column); field != nil && field.Readable {
fields[idx] = field fields[idx] = field
@ -104,6 +105,7 @@ func Scan(rows *sql.Rows, db *DB, initialized bool) {
values[idx] = &sql.RawBytes{} values[idx] = &sql.RawBytes{}
} }
} }
}
// pluck values into slice of data // pluck values into slice of data
isPluck := len(fields) == 1 && reflectValueType.Kind() != reflect.Struct isPluck := len(fields) == 1 && reflectValueType.Kind() != reflect.Struct

View File

@ -21,7 +21,7 @@ func TestDistinct(t *testing.T) {
} }
var names []string 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"}) AssertEqual(t, names, []string{"distinct", "distinct", "distinct", "distinct-2", "distinct-3"})
var names1 []string var names1 []string