GoFrame 數據查詢-All/One/Array/Value/Count

2022-04-02 09:31 更新

All/One/Array/Value/Count

這四個方法是數據查詢比較常用的方法,方法列表:

func (m *Model) All(where ...interface{} (Result, error)
func (m *Model) One(where ...interface{}) (Record, error)
func (m *Model) Array(fieldsAndWhere ...interface{}) ([]Value, error)
func (m *Model) Value(fieldsAndWhere ...interface{}) (Value, error)
func (m *Model) Count(where ...interface{}) (int, error)
func (m *Model) CountColumn(column string) (int, error)

簡要說明:

  1. ?All用于查詢并返回多條記錄的列表/數組。
  2. ?One用于查詢并返回單條記錄。
  3. ?Array用于查詢指定字段列的數據,返回數組。
  4. ?Value用于查詢并返回一個字段值,往往需要結合?Fields?方法使用。
  5. ?Count用于查詢并返回記錄數。

此外,也可以看得到這四個方法定義中也支持條件參數的直接輸入,參數類型與?Where?方法一致。但需要注意,其中?Array?和?Value?方法的參數中至少應該輸入字段參數。

使用示例:

// SELECT * FROM `user` WHERE `score`>60
Model("user").Where("score>?", 60).All()

// SELECT * FROM `user` WHERE `score`>60 LIMIT 1
Model("user").Where("score>?", 60).One()

// SELECT `name` FROM `user` WHERE `score`>60
Model("user").Fields("name").Where("score>?", 60).Array()

// SELECT `name` FROM `user` WHERE `uid`=1 LIMIT 1
Model("user").Fields("name").Where("uid", 1).Value()

// SELECT COUNT(1) FROM `user` WHERE `status` IN(1,2,3)
Model("user").Where("status", g.Slice{1,2,3}).Count()

Find*支持主鍵條件的數據查詢

方法列表:

func (m *Model) FindAll(where ...interface{}) (Result, error)
func (m *Model) FindOne(where ...interface{}) (Record, error)
func (m *Model) FindArray(fieldsAndWhere ...interface{}) (Value, error)
func (m *Model) FindValue(fieldsAndWhere ...interface{}) (Value, error)
func (m *Model) FindCount(where ...interface{}) (int, error)
func (m *Model) FindScan(pointer interface{}, where ...interface{}) error

?Find*?方法包含:?FindAll/FindOne/FineValue/FindCount/FindScan?,這些方法與?All/One/Array/Value/Count/Scan?方法的區(qū)別在于,當方法直接給定條件參數時,前者的效果與?WherePri?方法一致;而后者的效果與?Where?方法一致。也就是說?Find*?方法的條件參數支持智能主鍵識別特性。

使用示例:

// SELECT * FROM `scores` WHERE `id`=1
Model("scores").FindAll(1)

// SELECT * FROM `scores` WHERE `id`=1 LIMIT 1
Model("scores").FindOne(1)

// SELECT `name` FROM `scores` WHERE `id`=1
Model("scores").FindArray("name", 1)

// SELECT `name` FROM `scores` WHERE `id`=1 LIMIT 1
Model("user").FindValue("name", 1)

// SELECT COUNT(1) FROM `user`  WHERE `id`=1 
Model("user").FindCount(1)


以上內容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號