bee new 新建的项目目录中存在model目录,需要新建models.go 文件。使用官网的例子:
package main
import (
"http://github.com/astaxie/beego/orm"
)
type User struct {
Id int
Name string
Profile *Profile `orm:"rel(one)"` // OneToOne relation
Post []*Post `orm:"reverse(many)"` // 设置一对多的反向关系
}
type Profile struct {
Id int
Age int16
User *User `orm:"reverse(one)"` // 设置一对一反向关系(可选)
}
type Post struct {
Id int
Title string
User *User `orm:"rel(fk)"` //设置一对多关系
Tags []*Tag `orm:"rel(m2m)"` //多对多?
}
type Tag struct {
Id int
Name string
Posts []*Post `orm:"reverse(many)"` //设置多对多反向关系
}
func init() {
// 需要在init中注册定义的model,同时注册了多个。
orm.RegisterModel(new(User), new(Post), new(Profile), new(Tag))
}
看起来是用ER图就可以做出来,不需要将所有表结构都写出来。
然后是main.go:
package main
import (
"fmt"
"http://github.com/astaxie/beego/orm"
_ "http://github.com/go-sql-driver/mysql"
)
func init() {
orm.RegisterDriver("mysql", orm.DRMySQL) //参数1是数据库名字,参数2是数据库类型。表示使用Mysql(软件)数据库的mysql(数据库名字)数据库。
orm.RegisterDataBase("default", "mysql", "root:root@/orm_test?charset=utf8&loc=Asia%2FShanghai") //参数1是数据库别名,这里必须使用default; 参数2是数据库名称;参数3是数据的链接字符串,注意需要指定时区,不然是UTC时间。
}
func main() {
o := orm.NewOrm()
o.Using("default") // 默认使用 default,你可以指定为其他数据库
//下面是使用上面的model.go创建的示例数据
profile := new(Profile)
profile.Age = 30
user := new(User)
user.Profile = profile
user.Name = "slene"
fmt.Println(o.Insert(profile))
fmt.Println(o.Insert(user))
}
ORM 查询接口:
o := orm.NewOrm()
var r orm.RawSeter
r = o.Raw("UPDATE user SET name = ? WHERE name = ?", "testing", "slene") //使用Raw函数直接用SQL语句操作。
o := orm.NewOrm()
user := User{Name: "slene"}
err = o.Read(&user, "Name") //使用Read函数通过某个字段获取实体
fmt.Println(user.Id, user.Name)
var user User
user.Name = "slene"
user.IsActive = true
id, err := o.Insert(&user) //插入一行,返回的id为自增键id的值
user := User{Id: 1}
if o.Read(&user) == nil {
user.Name = "MyName"
if num, err := o.Update(&user,"Name"); err == nil { //更新一行的某个字段,num为返回的行数
fmt.Println(num)
}
}
if num, err := o.Delete(&User{Id: 1}); err == nil { //删除一行
fmt.Println(num)
}