我想创建一个通用的模型结构,将其嵌入到使用gorp (https://github.com/coopernurse/gorp)持久化MySQL数据库中的对象的结构中。我的理解是,这种组合是如何在Go中完成在强面向对象语言中通过继承完成的事情。
然而,我的运气并不好,因为我想在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结构中定义的)。
发布于 2013-04-22 01:28:22
有没有办法找出/使用我所在的类型(嵌入GorpModel的超类)
不是的。
我不知道构建您的解决方案的最佳方式,但是对于您试图在某种基类中实现的CRUD,只需将它们编写为函数即可。即。
func Create(gm interface{}) { // or whatever the signature should be
err := dbm.Insert(gm)
if err != nil {
panic(err)
}
}https://stackoverflow.com/questions/16133813
复制相似问题