Merge 84d9694eb32b31ea36d8a526d6a66b50709cd017 into 4c93473b2d05cc6a57be49f2a5713c087853088a
This commit is contained in:
commit
2dddf95f3e
@ -674,3 +674,27 @@ func TestSelectWithArrayInput(t *testing.T) {
|
|||||||
t.Errorf("Should have selected both age and name")
|
t.Errorf("Should have selected both age and name")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestPluckWithSelect(t *testing.T) {
|
||||||
|
DB.Save(&User{Name: "matematik7", Age: 25})
|
||||||
|
|
||||||
|
var userAges []string
|
||||||
|
err := DB.Model(&User{}).Where("age = ?", 25).Select("name || ' - ' || age as user_age").Pluck("user_age", &userAges).Error
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(userAges) != 1 || userAges[0] != "matematik7 - 25" {
|
||||||
|
t.Errorf("Should correctly pluck with select, got: %s", userAges)
|
||||||
|
}
|
||||||
|
|
||||||
|
userAges = userAges[:0]
|
||||||
|
err = DB.Model(&User{}).Where("age = ?", 25).Select("name || ' - ' || age as \"user_age\"").Pluck("user_age", &userAges).Error
|
||||||
|
if err != nil {
|
||||||
|
t.Error(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(userAges) != 1 || userAges[0] != "matematik7 - 25" {
|
||||||
|
t.Errorf("Should correctly pluck with select, got: %s", userAges)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
22
scope.go
22
scope.go
@ -938,14 +938,34 @@ func (scope *Scope) initialize() *Scope {
|
|||||||
return scope
|
return scope
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (scope *Scope) isQueryForColumn(query interface{}, column string) bool {
|
||||||
|
queryStr := strings.ToLower(fmt.Sprint(query))
|
||||||
|
if queryStr == column {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasSuffix(queryStr, "as "+column) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
if strings.HasSuffix(queryStr, "as \""+column+"\"") {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
|
||||||
func (scope *Scope) pluck(column string, value interface{}) *Scope {
|
func (scope *Scope) pluck(column string, value interface{}) *Scope {
|
||||||
dest := reflect.Indirect(reflect.ValueOf(value))
|
dest := reflect.Indirect(reflect.ValueOf(value))
|
||||||
scope.Search.Select(column)
|
|
||||||
if dest.Kind() != reflect.Slice {
|
if dest.Kind() != reflect.Slice {
|
||||||
scope.Err(fmt.Errorf("results should be a slice, not %s", dest.Kind()))
|
scope.Err(fmt.Errorf("results should be a slice, not %s", dest.Kind()))
|
||||||
return scope
|
return scope
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if query, ok := scope.Search.selects["query"]; !ok || !scope.isQueryForColumn(query, column) {
|
||||||
|
scope.Search.Select(column)
|
||||||
|
}
|
||||||
|
|
||||||
rows, err := scope.rows()
|
rows, err := scope.rows()
|
||||||
if scope.Err(err) == nil {
|
if scope.Err(err) == nil {
|
||||||
defer rows.Close()
|
defer rows.Close()
|
||||||
|
Loading…
x
Reference in New Issue
Block a user