標籤:調試 post password mode hub delete init rda err
beego架構中的rom支援mysql
項目中使用到mvc模式,總結下使用方式;
models中
package modelsimport ( //使用beego orm 必備 "github.com/astaxie/beego/orm" //使用的資料庫 必備 _ "github.com/go-sql-driver/mysql" // import your used driver)type BlogLogin struct { Id int64 Name string Pwd string WechatId string WechatInfo string CreateTime string LastLoginIp string LastLoginTime string}func RegisterDB() { //註冊 model orm.RegisterModel(new(BlogLogin)) //註冊預設資料庫 orm.RegisterDataBase("default", "mysql", "username:[email protected]/databasename?charset=utf8") //密碼為空白格式
當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 mainimport ( //調用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 controllersimport ( //使用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