# Gorm被其开发者声称为最棒的ORM,他们所言非虚
Gorm的功能非常强大,他允许程序员定义关系,实施数据迁移、串联多个查询以及执行其它很多高级的操作。除此之外,Gorm还能设置回调函数,这些回调函数在特定的数据时间发生时被执行。
下面的代码是我实现一个使用gorm的例子:
package main import ( "fmt" _ "github.com/go-sql-driver/mysql" "github.com/jinzhu/gorm" "time" ) type Post struct { //带结构标签,反引号来包围字符串 Id int Content string Author string `sql:"not null"` Comment []Comment CreatedAt time.Time } type Comment struct { Id int Content string Author string `sql:"not null"` PostId int `sql:"index"` CreatedAt time.Time } var Dbs *gorm.DB func init() { var err error Dbs,err = gorm.Open("mysql","用户名:密码@/数据库名?charset=utf8&parseTime=True&loc=Local") if err != nil { panic(err) } Dbs.AutoMigrate(&Post{},&Comment{}) } func main() { post := Post{ Content: "你好,中国", Author: "振彪", } fmt.Println(post) Dbs.Create(&post) comment := Comment{Content: "写的真好,非常不错",Author: "小白白"} //填加一条评论 Dbs.Model(&post).Association("Comment").Append(&comment) var readPost Post Dbs.Where("author = ?","万里,明月").First(&readPost) var comments []Comment Dbs.Model(&readPost).Related(&comments) fmt.Println(comments[0]) }