【问题标题】:Golang: Is there any way to access the "child" struct in the "parent" struct's methods in Go's composition model?Golang:有什么方法可以访问 Go 组合模型中“父”结构方法中的“子”?
【发布时间】: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 上调用UpdateInsert(定义在子 User 结构)。

【问题讨论】:

    标签: oop orm go


    【解决方案1】:

    有什么方法可以确定/使用我所在的类型(GorpModel 嵌入的超类)

    没有。

    我不知道构建您的解决方案的最佳方式,但对于您尝试在某种基类中实现的 CRUD,只需将它们编写为函数即可。即。

    func Create(gm interface{}) { // or whatever the signature should be
        err := dbm.Insert(gm)
        if err != nil {
            panic(err)
        }
    }
    

    【讨论】:

    • 谢谢您的好先生。这最终可以很好地满足我目前的需求。
    猜你喜欢
    • 2020-12-21
    • 2021-04-21
    • 2016-03-19
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-11
    • 1970-01-01
    相关资源
    最近更新 更多