douluanzhao6689 2019-04-25 16:12
浏览 118

具有单表继承“类型”列的Gorm(Golang)和数据库

I'm experimenting with using Go to read from a database that's been part of an existing Rails app. A few of the models and therefore tables use single table inheritance via a type column. In Rails/ActiveRecord, the presence of this column will create an automatic mapping to the appropriate model. If the table is animals and type is Dog, it will map to the Dog class; if it's Cat, it'll map to the Cat class. I want to setup something similar in Gorm.

Since it doesn't seem like Gorm has a default_scope option for a model, I'm using a new callback.

func scopedSearch(scope *gorm.Scope) {
    tablename := scope.TableName()
    switch tablename {
    case "table_using_sti":
        scope.Search.Where("type = ?", "MyModelName")
    default:
        return
    }
}

And then I register the callback in my main function:

db.Callback().Query().Before("gorm:query").Register("my_plugin:before_query", scopedSearch)

When I search against an instance using db.First or the model using db.Model(&MyModel{}).Where(...), it appears to be working. Is this the right way to handle it? Will this scope be respected by all of the query methods or is there something more direct or thorough?

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 求差集那个函数有问题,有无佬可以解决
    • ¥15 【提问】基于Invest的水源涵养
    • ¥20 微信网友居然可以通过vx号找到我绑的手机号
    • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
    • ¥15 解riccati方程组
    • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
    • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
    • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
    • ¥50 树莓派安卓APK系统签名
    • ¥65 汇编语言除法溢出问题