oop - 戈兰 : Is there any way to access the "child" struct in the "parent" struct's methods in Go's composition model?

标签 oop orm go

我想制作一个通用模型结构来嵌入将使用 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 用于跟踪它是否是新创建的模型,以及我们是否应该调用 UpdateInsertSave (目前在子 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/

相关文章:

python - 如何覆盖 odoo 方法?

go - 如何确保按 channel 生产和消费数据是安全的

select - 如何在 golang 的 select default case 中阻塞?

Gorm 多个事务以删除旧的搜索条件

c++ - 我应该从静态成员方法返回什么类型的指针

c# - 使用selectmany时删除 Entity Framework 引用约束错误

javascript - Sequelize ORM 中联接表的条件

"this"的 Ruby 模拟(从内部访问类实例)

java - 不要在子类的构造函数中创建父类(super class)实例,但完全合法

java - DDD 对于基于搜索的应用程序有好处吗?