diff --git a/orm/db.go b/orm/db.go index 20dc80f2..cefd5dfc 100644 --- a/orm/db.go +++ b/orm/db.go @@ -814,7 +814,11 @@ func (d *dbBase) ReadBatch(q dbQuerier, qs *querySet, mi *modelInfo, cond *Condi } } - query := fmt.Sprintf("SELECT %s FROM %s%s%s T0 %s%s%s%s", sels, Q, mi.table, Q, join, where, orderBy, limit) + sqlSelect := "SELECT" + if qs.distinct { + sqlSelect += " DISTINCT" + } + query := fmt.Sprintf("%s %s FROM %s%s%s T0 %s%s%s%s", sqlSelect, sels, Q, mi.table, Q, join, where, orderBy, limit) d.ins.ReplaceMarks(&query) diff --git a/orm/orm_queryset.go b/orm/orm_queryset.go index 5cc47617..106b62e5 100644 --- a/orm/orm_queryset.go +++ b/orm/orm_queryset.go @@ -61,6 +61,7 @@ type querySet struct { limit int64 offset int64 orders []string + distinct bool orm *orm } @@ -112,24 +113,30 @@ func (o querySet) OrderBy(exprs ...string) QuerySeter { return &o } +// add DISTINCT to SELECT +func (o querySet) Distinct() QuerySeter { + o.distinct = true + return &o +} + // set relation model to query together. // it will query relation models and assign to parent model. func (o querySet) RelatedSel(params ...interface{}) QuerySeter { - if len(params) == 0 { - o.relDepth = DefaultRelsDepth - } else { - for _, p := range params { - switch val := p.(type) { - case string: - o.related = append(o.related, val) - case int: - o.relDepth = val - default: - panic(fmt.Errorf(" wrong param kind: %v", val)) - } - } - } - return &o + if len(params) == 0 { + o.relDepth = DefaultRelsDepth + } else { + for _, p := range params { + switch val := p.(type) { + case string: + o.related = append(o.related, val) + case int: + o.relDepth = val + default: + panic(fmt.Errorf(" wrong param kind: %v", val)) + } + } + } + return &o } // set condition to QuerySeter. diff --git a/orm/types.go b/orm/types.go index b46be4fc..4347e46f 100644 --- a/orm/types.go +++ b/orm/types.go @@ -67,6 +67,7 @@ type QuerySeter interface { Limit(interface{}, ...interface{}) QuerySeter Offset(interface{}) QuerySeter OrderBy(...string) QuerySeter + Distinct() QuerySeter RelatedSel(...interface{}) QuerySeter Count() (int64, error) Exist() bool