Support count distinct

This commit is contained in:
huydx 2016-07-18 16:43:19 +09:00 committed by huydx
parent b507cdf93d
commit f159d05209
2 changed files with 12 additions and 0 deletions

View File

@ -298,6 +298,11 @@ func (s *DB) Count(value interface{}) *DB {
return s.NewScope(s.Value).count(value).db
}
// CountDistinct get how many distinct records for a model
func (s *DB) CountDistinct(value interface{}, columnName string) *DB {
return s.NewScope(s.Value).countDistinct(value, columnName).db
}
// Related get related associations
func (s *DB) Related(value interface{}, foreignKeys ...string) *DB {
return s.clone().NewScope(s.Value).related(value, foreignKeys...).db

View File

@ -921,6 +921,13 @@ func (scope *Scope) count(value interface{}) *Scope {
return scope
}
func (scope *Scope) countDistinct(value interface{}, column string) *Scope {
scope.Search.Select(fmt.Sprintf("count(%s)", column))
scope.Search.countingQuery = true
scope.Err(scope.row().Scan(value))
return scope
}
func (scope *Scope) typeName() string {
typ := scope.IndirectValue().Type()