//package main

//

//import (

// _ "myproject/routers"

// "github.com/astaxie/beego"

// "github.com/astaxie/beego/orm"

// "fmt"

//)

//

//func main() {

// //beego.SetStaticPath("/down1","download1") ,自定义设置多个静态文件处理目录

// beego.Run()

//}

// 上面是入门的案例, 下面是beego框架中orm的使用


package main


import (

_ "myproject/routers"

"github.com/astaxie/beego"

"github.com/astaxie/beego/orm"

"fmt"

)


type User struct{

Id int

Name string `orm:"size(100)"`

}


type Post struct{

Id int `orm:"auto"`

Title string `orm:"size(100)"`

User *User `orm:"rel(fk)"`

}


func init(){

// set default dabase

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


//register model

orm.RegisterModel(new(User))


//创建table

orm.RunSyncdb("default", false, true)

}


func main() {

//beego.SetStaticPath("/down1","download1") ,自定义设置多个静态文件处理目录

// 五,调试查询日志

//开发环境中,输出日志

// [ORM] - 2013-08-09 13:18:16 - [Queries/default] - [    db.Exec /     0.4ms] -   [INSERT INTO `user` (`name`) VALUES (?)] - `slene`

orm.Debug = true


o := orm.NewOrm()

user := User{Name:"slence"}


//一,通过orm进行增删改查

//insert

id, err := o.Insert(&user)

fmt.Printf("ID:%d, ERR: %v\n", id, err)


//update

user.Name = "astaxie"

num, err := o.Update(&user)

fmt.Printf("NUM:%d, ERR:%v\n", num, err)


//read one

u := User{Id:user.Id}

err = o.Read(&u)

fmt.Printf("ERR:%v\n", err)


//delete

num, err = o.Delete(&u)

fmt.Printf("NUM:%d, ERR:%v\n", num, err)


// 二,关联查询,主要还是在于Post的结构体中User字段定义了外键关联

var posts []*Post

qs := o.QueryTable("post")

num, err = qs.Filter("User_name", "slence").All(&posts)//不用:=是因为上面意见有num了,此处仅仅是修改

fmt.Printf("NUM:%d, ERR:%v\n", num, err)


// 三,使用原生的SQL语句进行查询

var maps []orm.Params

num, err= o.Raw("SELECT * FROM user").Values(&maps)

fmt.Printf("NUM:%d, ERR:%v\n", num, err)

for _, term := range maps{

fmt.Println(term["id"], ":", term["name"])

}


//四,事务的处理

//o.Begin

//。。。。

//o := NewOrm()

//user := User{Name:"slence"}

//id, err := o.Insert(&user)

//if err == nil{

// o.Commit()

//}else{

// o.Rollback()

//}


beego.Run()

}