【发布时间】:2013-04-22 01:28:21
【问题描述】:
我想制作一个通用模型结构以嵌入到结构中,该结构将使用gorp (https://github.com/coopernurse/gorp) 将对象持久保存在我的 MySQL 数据库中。据我了解,这种组合是在 Go 中完成在强 OO 语言中通过继承完成的事情的方式。
然而,我运气不佳,因为我想在 GorpModel 结构上定义所有 CRUD 方法,以避免在每个模型中重复它们,但这会导致 gorp(因为我现在使用它)假设我要与之交互的表称为GorpModel,因为gorp 使用了反射。这自然会导致错误,因为我的数据库中没有这样的表。
有什么方法可以确定/使用我所在的类型(GorpModel 嵌入的超类)来使下面的代码工作,还是我完全找错了树?
package models
import (
"fmt"
"reflect"
"github.com/coopernurse/gorp"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
type GorpModel struct {
New bool `db:"-"`
}
var dbm *gorp.DbMap = nil
func (gm *GorpModel) DbInit() {
gm.New = true
if dbm == nil {
db, err := sql.Open("mysql", "username:password@my_db")
if err != nil {
panic(err)
}
dbm = &gorp.DbMap{Db: db, Dialect: gorp.MySQLDialect{"InnoDB", "UTF8"}}
dbm.AddTable(User{}).SetKeys(true, "Id")
dbm.CreateTables()
}
}
func (gm *GorpModel) Create() {
err := dbm.Insert(gm)
if err != nil {
panic(err)
}
}
func (gm *GorpModel) Delete() int64 {
nrows, err := dbm.Delete(gm)
if err != nil {
panic(err)
}
return nrows
}
func (gm *GorpModel) Update() {
_, err := dbm.Update(gm)
if err != nil {
panic(err)
}
}
GorpModel 结构体的New 属性用于跟踪它是否是新创建的模型,以及我们是否应该在Save 上调用Update 或Insert(定义在子 User 结构)。
【问题讨论】: