The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
swqslwl

想知道 go 的 orm 框架都是如何映射结构体到表的?

  •  
  •   swqslwl · Aug 20, 2020 · 3200 views
    This topic created in 2284 days ago, the information mentioned may be changed or developed.

    通过结构体名去映射每个表的话,难道是有一个"注册"结构体的操作?不然的话是怎么找到项目中与表名对应的结构体的?

    package model
    
    import (
    	"github.com/jinzhu/gorm"
    )
    
    type ExaFileUploadAndDownload struct {
    	gorm.Model
    	Name string `json:"name" gorm:"comment:'文件名'"`
    	Url  string `json:"url" gorm:"comment:'文件地址'"`
    	Tag  string `json:"tag" gorm:"comment:'文件标签'"`
    	Key  string `json:"key" gorm:"comment:'编号'"`
    }
    
    }
    
    9 replies  •  2020-08-20 22:43:14 +08:00
    coderxy
    coderxy
    Aug 20, 2020
    1
    gorm:"comment:'文件名'" 就是这个起作用, 用反射获取 tag 的内容。然后一一对应
    pwli
    pwli
    Aug 20, 2020
    2
    可以给结构体写个 TableName()方法返回对应的表名,如果未定义该方法,框架可以使用默认映射策略,如:ExaFileUploadAndDownload -> exa_file_upload_and_download
    mcfog
    mcfog
    Aug 20, 2020
    3
    很多玩法,可以注册用反射解决,可以生成代码解决,也可以直接不解决,让用户 new 出来当参数传进来
    Leigg
    Leigg
    Aug 20, 2020 via Android
    4
    多了解 go 反射
    labulaka521
    labulaka521
    Aug 20, 2020
    5
    reflect
    tikazyq
    tikazyq
    Aug 20, 2020
    6
    反射
    chengxiao
    chengxiao
    Aug 20, 2020
    7
    func (ExaFileUploadAndDownload) TableName() string {
    return "表名"
    }
    wangyzj
    wangyzj
    Aug 20, 2020
    8
    我看代码里面写的是反射方式
    jessun1990
    jessun1990
    Aug 20, 2020❤️1
    9
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1843 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 04:37 · PVG 12:37 · LAX 20:37 · JFK 23:37
    ♥ Do have faith in what you're doing.