Beego framework orm operation exper operation

1. Basic use

  • 1. Initialize a project

  • 2. Install dependent packages

    // orm框架
    go get github.com/astaxie/beego/orm 
    // 使用什么数据库
    go get github.com/go-sql-driver/mysql
    
  • 3. main.goUse initfunctions to connect in

    import (
    	...
    	_ "github.com/go-sql-driver/mysql" // 必须加上
    )
    
    func init()  {
          
          
    	orm.RegisterDriver("mysql", orm.DRMySQL)
      // default必须要有,表示连接的数据库别名,可能是多个
    	orm.RegisterDataBase("default", "mysql", "用户名:密码@tcp(localhost:3306)/数据库名?charset=utf8mb4&parseTime=True&loc=Local")
    }
    
  • 4. Create a modelsfolder to store the data model (one-to-one correspondence with the database table)

    package models
    
    import "github.com/astaxie/beego/orm"
    
    type User struct {
          
          
    	Id int
    	Name string
    	Age int
    	Address string
    }
    
    //自定义表名,可以不写的会默认以下划线来分割驼峰命名的
    func (self *User) TableName () string  {
          
          
    	return "user"
    }
    
    func init() {
          
          
      // 使用exper表达式必须要注入模型,因此我们强制自己不管什么都要在模型中使用init函数来注入模型
    	orm.RegisterModel(new(User))
    }
    

Two, expertwo ways to create a handle using query

  • 1. Use the table name directly to create a handle

    type UserExper1Controller struct {
          
          
    	beego.Controller
    }
    
    func (ctx *UserExper1Controller) Get() {
          
          
    	o := orm.NewOrm()
      // 使用表名的方式来创建一个exper查询句柄
    	qs :=o.QueryTable("user")
      // 查询后的数据需要放到user这个结构体中
    	user := models.User{
          
          }
      // 使用expre表达式查询【name__exact】表示name完全匹配,One表示查询一条数据
    	qs.Filter("name__exact", "孙悟空").One(&user)
    	fmt.Println(user)
    	ctx.TplName="orm.html"
    }
    
  • 2. The way of using data model [recommended to use data model]

    type UserExper1Controller struct {
          
          
    	beego.Controller
    }
    
    func (ctx *UserExper1Controller) Get() {
          
          
    	o := orm.NewOrm()
      // 使用数据模型
    	userModel := new(models.User)
    	qs :=o.QueryTable(userModel)
    	user := models.User{
          
          }
    	qs.Filter("name__exact", "孙悟空").One(&user)
    	fmt.Println(user)
    	ctx.TplName="orm.html"
    }
    

Three, common experexpression operation symbols

No name For example Compare native SQL
1 exact/iexact name__exact(The namefield is equal to the following) where name = "xx"
2 contains/icontains name__contains(contain) where name like "%xx%"
3 gt/gte age__gt(Greater than/greater than or equal to) where age > 19
4 lt/lte age__lt(Less than/less than or equal to) where age < 19
5 startswith/istartswith name__startswith(Start with what) where name like "x%"
6 endswith/iendswith name__endswith(Ends with what) where name like "%x"
7 in age__in(In what range) where age in (1,2,3)
8 isnull qs.Filter("gender__isnull",true).One(&user)

Fourth, beegoopen the method of printing the ormcorresponding sqlsentence in

  • 1. Open globally, in main.go(recommended)

    func main() {
          
          
    	orm.Debug = true
    	beego.Run()
    }
    
  • 2. Partial development in the corresponding controller

    func (ctx *UserExper1Controller) Get() {
          
          
    	// 开始打印对应的sql
    	orm.Debug = true
    	...
    	ctx.TplName="orm.html"
    }
    

Five, Filteruse

  • 1. Query the desired field

    o := orm.NewOrm()
    // 使用数据模型
    userModel := new(models.User)
    qs := o.QueryTable(userModel)
    user := models.User{
          
          }
    // 需要查询出什么字段就在后面加
    qs.Filter("name__exact", "孙悟空").One(&user, "Name","Age")
    fmt.Println(user)
    ctx.Data["json"] = user
    ctx.ServeJSON()
    
  • 2. Multi-condition query

    o := orm.NewOrm()
    userModel := new(models.User)
    qs := o.QueryTable(userModel)
    user := models.User{
          
          }
    // 多条件的时候就多使用Filter
    qs.Filter("name__exact","孙悟空").Filter("age__gte", 2000).One(&user, "Name","Age")
    // 匹配的sql
    // select name, age from user where name = "孙悟空" and age >= 2000;
    ctx.Data["json"] = user
    ctx.ServeJSON()
    
  • 3. Use allmultiple query statements

    o := orm.NewOrm()
    userModel := new(models.User)
    qs := o.QueryTable(userModel)
    //返回多条语句要用切片
    user := []models.User{
          
          }
    //不加条件的查询
    qs.All(&user, "Name", "Age", "Address")
    // select name, age, address from user;
    ctx.Data["json"] = user
    ctx.ServeJSON()
    
  • 4. Use the Excludeexclude field to return

    o := orm.NewOrm()
    userModel := new(models.User)
    qs := o.QueryTable(userModel)
    user := []models.User{
          
          }
    qs.Exclude("name__exact", "孙悟空").All(&user)
    // select * from user where not name = "孙悟空";
    ctx.Data["json"] = user
    ctx.ServeJSON()
    
  • 5. Paging query statement

    o := orm.NewOrm()
    userModel := new(models.User)
    qs := o.QueryTable(userModel)
    user := []models.User{
          
          }
    //查询3条,从第一条开始查询
    qs.Limit(3).Offset(1).All(&user)
    // select * from user limit 1,3;
    ctx.Data["json"] = user
    ctx.ServeJSON()
    
  • 6. Sort by field

    o :=orm.NewOrm()
    userModel := new(models.User)
    qs := o.QueryTable(userModel)
    user := []models.User{
          
          }
    // 默认是升序,如果要降序的话就直接OrderBy("-age")
    qs.OrderBy("age").All(&user)
    ctx.Data["json"] = user
    ctx.ServeJSON()
    
  • 7. Determine whether it exists

    exist := qs.Filter("name__exact","猪八戒").Exist()
    // 返回true或者false
    fmt.Println(exist)
    
  • 8. Use the Updateupdate operation

    o := orm.NewOrm()
    userModel := new(models.User)
    num, err := o.QueryTable(userModel).Filter("name__exact", "孙悟空").Update(orm.Params{
          
          
      "Age": 2000,
    })
    fmt.Println(num) // 受影响的行数
    fmt.Println(err) // 错误
    ctx.Data["json"] = map[string]string{
          
          
      "code":    "0",
      "message": "成功",
    }
    ctx.ServeJSON()
    
  • 9, delete statement

    o := orm.NewOrm()
    userModel := new(models.User)
    num, err := o.QueryTable(userModel).Filter("name__exact","孙悟空").Delete()
    fmt.Println(num)
    fmt.Println(err)
    
  • 10. PrepareInsertInsert multiple statements at the same time

    Be careful to close at the end

    o := orm.NewOrm()
    users := []models.User{
          
          
      {
          
          Name: "孙悟空",Age: 1000,Address: "花果山"},
      {
          
          Name: "猪八戒",Age: 800,Address: "高老庄"},
      {
          
          Name: "沙增",Age: 500,Address: "流沙河"},
    }
    inserter, _ := o.QueryTable(new(models.User)).PrepareInsert()
    // 循环切片的数据
    for _, val := range users {
          
          
      id, err := inserter.Insert(&val)
      fmt.Println(id)
      fmt.Println(err)
    }
    //注意要记得关闭
    inserter.Close()
    
    // 但是插入多条数据建议使用InsertMulti
    o := orm.NewOrm()
    users := []models.User{
          
          
      {
          
          Name: "郭靖", Age: 30, Address: "襄阳"},
      {
          
          Name: "黄蓉", Age: 23, Address: "襄阳"},
    }
    num, err := o.InsertMulti(100, &users)
    fmt.Println(num, err)
    
  • 11. valuesUse (really jsonreturn the desired field)

    var maps []orm.Params
    o := orm.NewOrm()
    num, err := o.QueryTable(new(models.User)).Filter("age__gte", 100).Values(&maps, "Name", "Id", "Address", "Age")
    fmt.Println(num, err)
    ctx.Data["json"] = maps
    ctx.ServeJSON()
    
  • 12. The ValuesListdefault return is 1000 data

    var lists []orm.ParamsList
    o := orm.NewOrm()
    // 返回数组,里面嵌套根据字段嵌套
    num, err := o.QueryTable(new(models.User)).ValuesList(&lists, "Name")
    fmt.Println(num, err)
    ctx.Data["json"] = lists
    ctx.ServeJSON()
    
    // 返回的数据结构
    [
      [
        "唐三藏"
      ],
      [
        "孙悟空"
      ]
    ]
    
  • 13. ValuesFlatFlattening returns an array

    var lists orm.ParamsList
    o := orm.NewOrm()
    // 返回数组,里面嵌套根据字段嵌套
    num, err := o.QueryTable(new(models.User)).ValuesFlat(&lists, "Name")
    fmt.Println(num, err)
    ctx.Data["json"] = lists
    ctx.ServeJSON()
    
    // 返回数据
    [
      "唐三藏",
      "孙悟空",
    ]
    
  • 14. UpdateAdd values ​​based on existing fields

    o := orm.NewOrm()
    num, err := o.QueryTable(new(models.User)).Filter("name__exact", "孙悟空").Update(orm.Params{
          
          
      "Age": orm.ColValue(orm.ColAdd, 100),
    })
    // 对应的原生sql
    // update user set age=age+100 where name = "孙悟空";
    fmt.Println(num, err)
    

    Corresponding other methods are

    • ColAddAdd to

    • ColMinuscut back

    • ColMultiplymultiplication

    • ColExceptdivision

Guess you like

Origin blog.csdn.net/kuangshp128/article/details/109383685