diff --git a/main.go b/main.go index 97cff7db..44bc2074 100644 --- a/main.go +++ b/main.go @@ -326,6 +326,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 diff --git a/scope.go b/scope.go index 9a237998..556dd8bd 100644 --- a/scope.go +++ b/scope.go @@ -947,6 +947,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()