我想制作一个通用模型结构来嵌入将使用 gorp
的结构中( https://github.com/coopernurse/gorp ) 将对象保存在我的 MySQL 数据库中。据我了解,这种组合是人们如何在 Go 中完成在强 OO 语言中通过继承完成的事情。
但是,我的运气不太好,因为我想在 GorpModel
上定义所有 CRUD 方法。 struct,以避免在每个模型中重复它们,但这会导致 gorp
(因为我现在正在使用它)假设我想要与之交互的表名为 GorpModel
由于反射(reflect)gorp
用途。这自然会导致错误,因为我的数据库中没有这样的表。
有什么方法可以找出/使用我所处的类型(GorpModel
嵌入的父类(super class))来使下面的代码正常工作,或者我完全找错了树?
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)
}
}
New
GorpModel
的属性(property)struct 用于跟踪它是否是新创建的模型,以及我们是否应该调用 Update
或Insert
上Save
(目前在子 User
结构中定义)。
最佳答案
Is there any way to figure out / use which type I'm in (the superclass which GorpModel is embedded in)
没有。
我不知道构建解决方案的最佳方法,但是对于您尝试在某种基类中实现的 CRUD,只需将它们编写为函数即可。即。
func Create(gm interface{}) { // or whatever the signature should be
err := dbm.Insert(gm)
if err != nil {
panic(err)
}
}
关于oop - 戈兰 : Is there any way to access the "child" struct in the "parent" struct's methods in Go's composition model?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16133813/