Files
gf/database/gdb/gdb_model_order_group.go

78 lines
1.8 KiB
Go
Raw Permalink Normal View History

// Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
//
// This Source Code Form is subject to the terms of the MIT License.
// If a copy of the MIT was not distributed with this file,
// You can obtain one at https://github.com/gogf/gf.
package gdb
2021-12-22 20:51:03 +08:00
import (
"strings"
2022-03-09 21:02:08 +08:00
"github.com/gogf/gf/v2/text/gstr"
"github.com/gogf/gf/v2/util/gconv"
2021-12-22 20:51:03 +08:00
)
// Order sets the "ORDER BY" statement for the model.
//
// Eg:
// Order("id desc")
2022-01-17 17:14:40 +08:00
// Order("id", "desc").
2022-03-09 21:02:08 +08:00
// Order("id desc,name asc")
// Order("id desc").Order("name asc")
2022-01-17 17:14:40 +08:00
// Order(gdb.Raw("field(id, 3,1,2)")).
2021-12-22 20:51:03 +08:00
func (m *Model) Order(orderBy ...interface{}) *Model {
if len(orderBy) == 0 {
return m
}
model := m.getModel()
if model.orderBy != "" {
model.orderBy += ","
}
2022-03-09 21:02:08 +08:00
for _, v := range orderBy {
switch v.(type) {
case Raw, *Raw:
2022-01-07 21:06:49 +08:00
model.orderBy += gconv.String(v)
return model
2021-12-22 20:51:03 +08:00
}
}
2022-03-09 21:02:08 +08:00
model.orderBy += model.db.GetCore().QuoteString(gstr.JoinAny(orderBy, " "))
2022-01-07 21:06:49 +08:00
return model
}
// OrderAsc sets the "ORDER BY xxx ASC" statement for the model.
func (m *Model) OrderAsc(column string) *Model {
if len(column) == 0 {
return m
}
return m.Order(column + " ASC")
}
// OrderDesc sets the "ORDER BY xxx DESC" statement for the model.
func (m *Model) OrderDesc(column string) *Model {
if len(column) == 0 {
return m
}
return m.Order(column + " DESC")
}
// OrderRandom sets the "ORDER BY RANDOM()" statement for the model.
func (m *Model) OrderRandom() *Model {
model := m.getModel()
model.orderBy = "RAND()"
return model
}
// Group sets the "GROUP BY" statement for the model.
func (m *Model) Group(groupBy ...string) *Model {
if len(groupBy) == 0 {
return m
}
model := m.getModel()
if model.groupBy != "" {
model.groupBy += ","
}
model.groupBy += model.db.GetCore().QuoteString(strings.Join(groupBy, ","))
return model
}