beego orm mysql_BeeGo ORM 的使用

这篇博客介绍了如何在BeeGo应用中使用ORM进行MySQL数据库操作。首先,展示了如何定义模型结构,如User、Profile、Post和Tag,并通过`orm.RegisterModel`注册。接着,初始化数据库连接,包括注册驱动和数据源。在主函数中,创建并插入示例数据。最后,演示了ORM的查询接口,包括更新、读取、插入和删除记录的操作。
摘要由CSDN通过智能技术生成

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)

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值