一、模型(Models)

1、beego-orm的相关特性 

  •  支持 Go 的所有类型存储 
  • -轻松上手,采用简单的 CRUD 风格 
  • -自动 Join 关联表 
  •  跨数据库兼容查询 
  • 允许直接使用 SQL 查询/映射 
  •  严格完整的测试保证 ORM 的稳定与健壮 

2、安装ORM

go get github.com/astaxie/beego/orm

3、ORM接口

type Ormer interface {
Read(interface{}, …string) error
ReadOrCreate(interface{}, string, …string) (bool, int64, error)
Insert(interface{}) (int64, error)
InsertMulti(int, interface{}) (int64, error)
Update(interface{}, …string) (int64, error)
Delete(interface{}) (int64, error)
LoadRelated(interface{}, string, …interface{}) (int64, error)
QueryM2M(interface{}, string) QueryM2Mer
QueryTable(interface{}) QuerySeter
Using(string) error
Begin() error
Commit() error
Rollback() error
Raw(string, …interface{}) RawSeter
Driver() Driver
}

3、数据库的设置,支持三种数据库

将你需要使用的 driver 加入 import 中

import (
    _ "github.com/go-sql-driver/mysql"
    _ "github.com/lib/pq"
    _ "github.com/mattn/go-sqlite3"
) 

引入包后,需要注册

#连接mysql数据库

orm.RegisterDataBase("default", "mysql", "root:root@/orm_db?charset=utf8",30)

orm.RegisterModel(new(User))

4、操作model的方法

    o := orm.NewOrm()
    user := User{Name: "slene"}
    // insert
    id, err := o.Insert(&user)
    // update
    user.Name = "astaxie"
    num, err := o.Update(&user)
    // read one
    u := User{Id: user.Id}
    err = o.Read(&u)
    // delete
    num, err = o.Delete(&u)

在mysql中要小写,这是约写。大写会对应小写,需加下划线。

AuthUser -> auth_user
Auth_User -> auth__user
DB_AuthUser -> d_b__auth_user

  

示例:

创建表语句

use test
create table user_info(id int(11) auto_increment, username varchar(32), password varchar(256), primary key(id));

mysql> show tables;
+----------------+
| Tables_in_test |
+----------------+
| user_info |
+----------------+
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_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.RegisterDataBase("default", "mysql", "root:qwe!23@tcp(127.0.0.1:3306)/test?charset=utf8", 30)
	orm.RegisterModel(new(UserInfo))

	o := orm.NewOrm()
	//插入数据
	//user := UserInfo{Username: "zhangsan", Password: "123456"}
	//id, err := o.Insert(&user)

	//更新数据
	user := UserInfo{Username: "list", Password: "123456"}
	user.Id = 1
	user.Username = "nulige"
	id, err := o.Update(&user)

	//以字符串,直接输出
	c.Ctx.WriteString(fmt.Sprintf("id:%d err:%v", id, err))
}

执行结果:

D:\GoFiles\src\WEB>bee run
______
| ___ \
| |_/ /  ___   ___
| ___ \ / _ \ / _ \
| |_/ /|  __/|  __/
\____/  \___| \___| v1.10.0
2019/02/13 17:09:58 INFO     ▶ 0001 Using 'WEB' as 'appname'
2019/02/13 17:09:58 INFO     ▶ 0002 Initializing watcher...
web/controllers
web/routers
2019/02/13 17:10:02 SUCCESS  ▶ 0003 Built Successfully!
2019/02/13 17:10:02 INFO     ▶ 0004 Restarting 'WEB.exe'...
2019/02/13 17:10:02 SUCCESS  ▶ 0005 './WEB.exe' is running...
2019/02/13 17:10:02.621 [I] [asm_amd64.s:1333]  http server Running on http://:8
080
[beego] 2019/02/13 - 17:10:04 |      127.0.0.1| 200 |         24ms|   match| GET
      /test_model   r:/test_model

打开浏览器,访问:

http://127.0.0.1:8080/test_model

返回结果:
id:1 err:<nil>

#mysql数据库中查询结果
mysql>use test

#修改前是list
mysql> select * from user_info;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
|  1 | list     | 123456   |
+----+----------+----------+
1 row in set (0.00 sec)

#修改后变成nulige
mysql> select * from user_info;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
|  1 | nulige   | 123456   |
+----+----------+----------+
1 row in set (0.00 sec)

  

示例:读取数据

mysql数据库中数据

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

读取数据

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.RegisterDataBase("default", "mysql", "root:qwe!23@tcp(127.0.0.1:3306)/test?charset=utf8", 30)
	orm.RegisterModel(new(UserInfo))

	o := orm.NewOrm()
	//读取
	user := UserInfo{Username: "nulige", Password: "123456"}
	user.Id = 1

	o.Read(&user)

	//直接输出
	c.Ctx.WriteString(fmt.Sprintf("user info:%v", user))
}

执行结果:

在浏览器中输入:
http://127.0.0.1:8080/test_model

结果:
user info:{1 nulige 123456}

 删除

 删除数据    

stmt, err = db.Prepare("delete from user_info where uid=?")   
res, err = stmt.Exec(id)

  

5、SQL直接查询

routers/router.go

package routers

import (
	"web/controllers"

	"github.com/astaxie/beego"
)

func init() {
	beego.Router("/", &controllers.MainController{})
	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()

	//原生sql语句读取
	var maps []orm.Params
	o.Raw("select * from user_info").Values(&maps)

	for _, v := range maps {
		c.Ctx.WriteString(fmt.Sprintf("user info:%v", v))
	}
}

执行结果

http://127.0.0.1:8080/test_model

返回结果:
user info:map[id:1 username:nulige password:123456]

6、通过QueryRows读取
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()

	//通过QueryRows读取
	var users []UserInfo
	o.Raw("select * from user_info").QueryRows(&users)
	c.Ctx.WriteString(fmt.Sprintf("user info:%v", users))
}

执行结果:

http://127.0.0.1:8080/test_model

返回结果:
user info:[{1 nulige 123456}]