Go语言之高级篇beego框架之model设计构造查询

时间:2023-01-27 09:45:08

一、model设计构造查询

QueryBuilder 提供了一个简便,流畅的 SQL 查询构造器。在不影响代码可读性的前提下用来快速的建立 SQL 语句。

QueryBuilder 在功能上与 ORM 重合, 但是各有利弊。ORM 更适用于简单的 CRUD 操作,而 QueryBuilder 则更适用于复杂的查询,例如查询中包含子查询和多重联结。

1、model设计构造查询

示例:

// User 包装了下面的查询结果
type User struct {
Name string
Age int
}
var users []User // 获取 QueryBuilder 对象. 需要指定数据库驱动参数。
// 第二个返回值是错误对象,在这里略过
qb, _ := orm.NewQueryBuilder("mysql") // 构建查询对象
qb.Select("user.name",
"profile.age").
From("user").
InnerJoin("profile").On("user.id_user = profile.fk_user").
Where("age > ?").
OrderBy("name").Desc().
Limit(10).Offset(0) // 导出 SQL 语句
sql := qb.String() // 执行 SQL 语句
o := orm.NewOrm()
o.Raw(sql, 20).QueryRows(&users)

 

2、通过构建查询操作数据库

示例1:

mysql数据库

mysql> select * from user_info;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | nulige | 123456 |
+----+----------+----------+
1 row in set (0.00 sec)

示例:

routers/router.go

package routers

import (
"web/controllers" "github.com/astaxie/beego"
) func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/test_input", &controllers.TestInputController{}, "get:Get;post:Post")
beego.Router("/test_model", &controllers.TestModelController{}, "get:Get;post:Post")
} 
controllers/testModel.go
package controllers

import (
"fmt" "github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
) //由于model这个名字叫 UserInfo 那么操作的表其实 user_info
type UserInfo struct {
Id int64
Username string
Password string
} type TestModelController struct {
beego.Controller
} func (c *TestModelController) Get() {
orm.Debug = true // 是否开启调试模式 调试模式下会打印出sql语句
orm.RegisterDataBase("default", "mysql", "root:qwe!23@tcp(127.0.0.1:3306)/test?charset=utf8", 30)
orm.RegisterModel(new(UserInfo)) o := orm.NewOrm() //构建查询
//采用QueryBuilder方式
var users []UserInfo
qb, _ := orm.NewQueryBuilder("mysql")
qb.Select("password").From("user_info").Where("username= ?").Limit(1) sql := qb.String()
o.Raw(sql, "nulige").QueryRows(&users) c.Ctx.WriteString(fmt.Sprintf("user info:%v", users))
}

执行结果:

http://127.0.0.1:8080/test_model

返回结果:

user info:[{0  123456}] 

3、完整的API接口

type QueryBuilder interface {
Select(fields ...string) QueryBuilder
From(tables ...string) QueryBuilder
InnerJoin(table string) QueryBuilder
LeftJoin(table string) QueryBuilder
RightJoin(table string) QueryBuilder
On(cond string) QueryBuilder
Where(cond string) QueryBuilder
And(cond string) QueryBuilder
Or(cond string) QueryBuilder
In(vals ...string) QueryBuilder
OrderBy(fields ...string) QueryBuilder
Asc() QueryBuilder
Desc() QueryBuilder
Limit(limit int) QueryBuilder
Offset(offset int) QueryBuilder
GroupBy(fields ...string) QueryBuilder
Having(cond string) QueryBuilder
Subquery(sub string, alias string) string
String() string
}

  

示例:

示例1:

mysql数据库

mysql> select * from user_info;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 1 | nulige | 123456 |
+----+----------+----------+
1 row in set (0.00 sec)

示例:

routers/router.go

package routers

import (
"web/controllers" "github.com/astaxie/beego"
) func init() {
beego.Router("/", &controllers.MainController{})
beego.Router("/test_input", &controllers.TestInputController{}, "get:Get;post:Post")
beego.Router("/test_model", &controllers.TestModelController{}, "get:Get;post:Post")
} 
controllers/testModel.go
package controllers

import (
"fmt" "github.com/astaxie/beego"
"github.com/astaxie/beego/orm"
_ "github.com/go-sql-driver/mysql"
) //由于model这个名字叫 UserInfo 那么操作的表其实 user_info
type UserInfo struct {
Id int64
Username string
Password string
} type TestModelController struct {
beego.Controller
} func (c *TestModelController) Get() {
orm.Debug = true // 是否开启调试模式 调试模式下会打印出sql语句
orm.RegisterDataBase("default", "mysql", "root:qwe!23@tcp(127.0.0.1:3306)/test?charset=utf8", 30)
orm.RegisterModel(new(UserInfo)) o := orm.NewOrm() var users []UserInfo
qb, _ := orm.NewQueryBuilder("mysql")
qb.Select("password").From("user_info").Where("username= 'nulige'").And("id=1").Limit(1) sql := qb.String()
o.Raw(sql).QueryRows(&users)
c.Ctx.WriteString(fmt.Sprintf("user info:%v", users))
}

执行结果:

http://127.0.0.1:8080/test_model

返回结果:

user info:[{0  123456}]