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

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

  •  
  •   swqslwl · Aug 20, 2020 · 2801 views
    This topic created in 2118 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
        1
    coderxy  
       Aug 20, 2020
    gorm:"comment:'文件名'" 就是这个起作用, 用反射获取 tag 的内容。然后一一对应
    pwli
        2
    pwli  
       Aug 20, 2020
    可以给结构体写个 TableName()方法返回对应的表名,如果未定义该方法,框架可以使用默认映射策略,如:ExaFileUploadAndDownload -> exa_file_upload_and_download
    mcfog
        3
    mcfog  
       Aug 20, 2020
    很多玩法,可以注册用反射解决,可以生成代码解决,也可以直接不解决,让用户 new 出来当参数传进来
    Leigg
        4
    Leigg  
       Aug 20, 2020 via Android
    多了解 go 反射
    labulaka521
        5
    labulaka521  
       Aug 20, 2020
    reflect
    tikazyq
        6
    tikazyq  
       Aug 20, 2020
    反射
    chengxiao
        7
    chengxiao  
       Aug 20, 2020
    func (ExaFileUploadAndDownload) TableName() string {
    return "表名"
    }
    wangyzj
        8
    wangyzj  
       Aug 20, 2020
    我看代码里面写的是反射方式
    jessun1990
        9
    jessun1990  
       Aug 20, 2020   ❤️ 1
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   968 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 51ms · UTC 21:54 · PVG 05:54 · LAX 14:54 · JFK 17:54
    ♥ Do have faith in what you're doing.