2019-go-01

beego orm

已支持数据库驱动:

  • MySQL:github.com/go-sql-driver/mysql
  • PostgreSQL:github.com/lib/pq

导入驱动

import (
    _ "github.com/go-sql-driver/mysql"
)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// models/User.go

type Users struct {
Id int
Name string
Pwd string
Age int
Sex string
}

/*
//我们也可以使用Tag对属性进行详细的设置
type Users struct {
Id int `pk:"auto;column(id)"` //设置主键自增长 列名设为id
Name string `orm:"size(15);column(name)"` //设置varchar长度为15 列名为name
Pwd string `orm:"size(15);column(pwd)"`
Age int `orm:"column(age)"`
Sex string `orm:"size(15);column(sex)"`
}
*/


//初始化
func init() {
//注册数据驱动
// orm.RegisterDriver("mysql", orm.DR_MySQL)
// mysql / sqlite3 / postgres 这三种是默认已经注册过的,所以可以无需设置
//注册数据库 ORM 必须注册一个别名为 default 的数据库,作为默认使用
orm.RegisterDataBase("default", "mysql", "root:123456@tcp(127.0.0.1:3306)/HelloBeego")
//注册模型
orm.RegisterModel(new(Users))
//自动创建表 参数二为是否开启创建表 参数三是否更新表
orm.RunSyncdb("default", true, true)
}
1
2
3
4
5
6
7
orm.RegisterDataBase("default", "mysql", "root:root@/orm_test?charset=utf8", maxIdle, maxConn)

// 参数1 数据库的别名,用来在 ORM 中切换数据库使用
// 参数2 数据库驱
// 参数3 对应的连接字符串
// 参数4(可选) 设置最大空闲连接
// 参数5(可选) 设置最大数据库连接 (go >= 1.2)

模型设置详解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
忽略字段
设置 - 即可忽略 struct 中的字段
AnyField string `orm:"-"`

auto
当 Field 类型为 int, int32, int64, uint, uint32, uint64 时,可以设置字段为自增健
当模型定义里没有主键时,符合上述类型且名称为 Id 的 Field 将被视为自增健。

pk
设置为主键,适用于自定义其他类型为主键

null
数据库表默认为 NOT NULL,设置 null 代表 ALLOW NULL
Name string `orm:"null"

index
为单个字段增加索引

unique
为单个字段增加 unique 键
Name string `orm:"unique"`

column
为字段设置 db 字段的名称
Name string `orm:"column(user_name)"`

size
string 类型字段默认为 varchar(255)
设置 size 以后,db type 将使用 varchar(size)
Title string `orm:"size(60)"`


digits / decimals
设置 float32, float64 类型的浮点精度
Money float64 `orm:"digits(12);decimals(4)"`
总长度 12 小数点后 4 位 eg: 99999999.9999

auto_now / auto_now_add
Created time.Time `orm:"auto_now_add;type(datetime)"`
Updated time.Time `orm:"auto_now;type(datetime)"`
auto_now 每次 model 保存时都会对时间自动更新
auto_now_add 第一次保存时才设置时间
对于批量的 update 此设置是不生效的
type
设置为 date 时,time.Time 字段的对应 db 类型使用 date


Created time.Time `orm:"auto_now_add;type(date)"`
设置为 datetime 时,time.Time 字段的对应 db 类型使用 datetime
Created time.Time `orm:"auto_now_add;type(datetime)"`

default
为字段设置默认值,类型必须符合(目前仅用于级联删除时的默认值)
Status int `orm:"default(1)"`