github.com/gogf/gf/v2@v2.7.4/database/gdb/gdb_model_order_group.go (about)

     1  // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
     2  //
     3  // This Source Code Form is subject to the terms of the MIT License.
     4  // If a copy of the MIT was not distributed with this file,
     5  // You can obtain one at https://github.com/gogf/gf.
     6  
     7  package gdb
     8  
     9  import (
    10  	"strings"
    11  
    12  	"github.com/gogf/gf/v2/text/gstr"
    13  	"github.com/gogf/gf/v2/util/gconv"
    14  )
    15  
    16  // Order sets the "ORDER BY" statement for the model.
    17  //
    18  // Eg:
    19  // Order("id desc")
    20  // Order("id", "desc").
    21  // Order("id desc,name asc")
    22  // Order("id desc").Order("name asc")
    23  // Order(gdb.Raw("field(id, 3,1,2)")).
    24  func (m *Model) Order(orderBy ...interface{}) *Model {
    25  	if len(orderBy) == 0 {
    26  		return m
    27  	}
    28  	model := m.getModel()
    29  	if model.orderBy != "" {
    30  		model.orderBy += ","
    31  	}
    32  	for _, v := range orderBy {
    33  		switch v.(type) {
    34  		case Raw, *Raw:
    35  			model.orderBy += gconv.String(v)
    36  			return model
    37  		}
    38  	}
    39  	model.orderBy += model.db.GetCore().QuoteString(gstr.JoinAny(orderBy, " "))
    40  	return model
    41  }
    42  
    43  // OrderAsc sets the "ORDER BY xxx ASC" statement for the model.
    44  func (m *Model) OrderAsc(column string) *Model {
    45  	if len(column) == 0 {
    46  		return m
    47  	}
    48  	return m.Order(column + " ASC")
    49  }
    50  
    51  // OrderDesc sets the "ORDER BY xxx DESC" statement for the model.
    52  func (m *Model) OrderDesc(column string) *Model {
    53  	if len(column) == 0 {
    54  		return m
    55  	}
    56  	return m.Order(column + " DESC")
    57  }
    58  
    59  // OrderRandom sets the "ORDER BY RANDOM()" statement for the model.
    60  func (m *Model) OrderRandom() *Model {
    61  	model := m.getModel()
    62  	model.orderBy = m.db.OrderRandomFunction()
    63  	return model
    64  }
    65  
    66  // Group sets the "GROUP BY" statement for the model.
    67  func (m *Model) Group(groupBy ...string) *Model {
    68  	if len(groupBy) == 0 {
    69  		return m
    70  	}
    71  	model := m.getModel()
    72  	if model.groupBy != "" {
    73  		model.groupBy += ","
    74  	}
    75  	model.groupBy += model.db.GetCore().QuoteString(strings.Join(groupBy, ","))
    76  	return model
    77  }