时间:2021-07-01 10:21:17 帮助过:21人阅读
当model创建了一个type ,在RegisterDB中调用该方法创建表
//orm.RunSyncdb("default", false, true)
创建表结构案例
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)"` }
然后main中初始化,创建表
package main import ( //调用models中registerDB方法注册 "blog/models" //设置路由,必备 _ "blog/routers" //beego控制器使用必备 "github.com/astaxie/beego" //开启调试默认 "github.com/astaxie/beego/orm" ) func init() { models.RegisterDB() } func main() { orm.Debug = true beego.Run() }
接下来在controller中使用
package controllers import ( //使用model中的类型BlogLogin "blog/models" //打印数据库查出来的结果 "fmt" //beego控制器必备 "github.com/astaxie/beego" //使用orm 中的查询方法 "github.com/astaxie/beego/orm" ) type AdminLoginController struct { beego.Controller } func (this *AdminLoginController) Get() { this.TplName = "AdminLogin.html" } func (this *AdminLoginController) Post() { name := this.Input().Get("name") pwd := this.Input().Get("pwd") o := orm.NewOrm() // read one login := models.BlogLogin{Name: name, Pwd: pwd} //read默认根据主键查询,下面我设置的为跟怒name 和pwd 查询 err := o.Read(&login, "Name", "Pwd") if err != nil { fmt.Printf("ERR: %v\n", err) this.Redirect("/adminlogin.html", 301) return } fmt.Printf("Data: %v\n", login)
this.Redirect("/admin.html", 301) return }
下面为一些标准的sql使用:
// 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)
详情来自官网:https://beego.me/docs/mvc/model/orm.md
beego orm mysql
标签:调试 post password mode hub delete init rda err