Beego框架:高階查詢
阿新 • • 發佈:2018-11-21
isnull:判斷某個欄位是否為null
func (this *OperatorsController) GetIsNull() { user := models.User{} var users []*models.User orm := orm.NewOrm()//建立orm qs := orm.QueryTable(user)//建立控制代碼 n, err := qs.Filter("name__isnull", false).All(&users) if err != nil { this.Ctx.WriteString("查詢失敗!") return } fmt.Println("n = ", n) for _, u := range users { fmt.Println("u = ", u) } this.Ctx.WriteString("查詢成功!") }
in:和sql中得in含義相同,通常和Filter結合使用
func (this *OperatorsController) GetIn() { user := models.User{} var users []*models.User //建立orm orm := orm.NewOrm() //建立控制代碼 qs := orm.QueryTable(user) //SELECT * FROM USER WHERE id IN(2, 5, 6); /*buffer := []int{ 13, 14, 15, 16} n, err := qs.Filter("id__in", buffer).All(&users)*/ n, err := qs.Filter("id__in", 13, 14, 15, 16).All(&users) if err != nil { this.Ctx.WriteString("查詢失敗!") return } fmt.Println("n = ", n) for _, u := range users { fmt.Println("u = ", u) } this.Ctx.WriteString("查詢成功!") }
istartswith:判斷某個欄位是否以指定內容開始
func (this *OperatorsController) GetStartswith() { user := models.User{} var users []*models.User //建立orm orm := orm.NewOrm() //建立控制代碼 qs := orm.QueryTable(user) //SELECT * FROM USER WHERE NAME LIKE '杜%' n, err := qs.Filter("name__startswith", "B").All(&users) if err != nil { this.Ctx.WriteString("查詢失敗!") return } fmt.Println("n = ", n) for _, u := range users { fmt.Println("u = ", u) } this.Ctx.WriteString("查詢成功!") }
gt:大於,通常和Filter結合使用
func (this *OperatorsController) GetGt() {
user := models.User{}
var users []*models.User
//建立orm
orm := orm.NewOrm()
//建立控制代碼
qs := orm.QueryTable(user)
//SELECT * FROM USER WHERE id > 2;
n, err := qs.Filter("id__gt", 14).All(&users)
if err != nil {
this.Ctx.WriteString("查詢失敗!")
return
}
fmt.Println("n = ", n)
for _, u := range users {
fmt.Println("u = ", u)
}
this.Ctx.WriteString("查詢成功!")
}
contains:判斷某個欄位是否 包含指定欄位
func (this *OperatorsController) GetContains() {
user := models.User{}
//建立使用者指標切片,用於儲存查詢結果
var users []*models.User
//建立orm
orm := orm.NewOrm()
//建立控制代碼
qs := orm.QueryTable(user)
//SELECT * FROM USER WHERE NAME LIKE '%紫%';
n, err := qs.Filter("name__contains", "o").All(&users)
if err != nil {
this.Ctx.WriteString("查詢失敗!")
return
}
fmt.Println("n = ", n)
for _, u := range users {
fmt.Println("u = ", u)
}
this.Ctx.WriteString("查詢成功!")
}
exact:對某個條件取反
func (this *OperatorsController) GetExact() {
user := models.User{}
//建立orm
orm := orm.NewOrm()
//建立控制代碼
qs := orm.QueryTable("user")
//SELECT * FROM USER WHERE id = 7;
//在user表中查詢id等於12的使用者
err := qs.Filter("id__exact", 12).One(&user)
if err != nil {
this.Ctx.WriteString("查詢失敗!")
return
}
fmt.Println("user = ", user)
this.Ctx.WriteString("查詢成功!")
}
學院Go語言視訊主頁
https://edu.csdn.net/lecturer/1928
清華團隊帶你實戰區塊鏈開發
掃碼獲取海量視訊及原始碼 QQ群:721929980