leeraya
V2EX  ›  问与答

有一点不解, gorm 怎么联系 struct 和数据库表的

  •  
  •   leeraya · Oct 21, 2022 · 1709 views
  •   You need to sign in to view this topic
    This topic created in 1461 days ago, the information mentioned may be changed or developed.

    最近在读 gorm 的英文文档,不知道哪里读漏了,通常就是声明一个 struct 的实例就往创建,查询方法里丢。 gorm 是怎么样认定这个 struct 和程序员想要操作的表的关系的?难道就只通过名字对应? https://gorm.io/docs/models.html

    4 replies  •  2022-10-21 22:57:01 +08:00
    ihuanran
        1
    ihuanran  
       Oct 21, 2022
    可以实现 TableName() string 方法指定表名,不然就用 struct 名字
    KotlinAmai
        2
    KotlinAmai  
       Oct 21, 2022   ❤️ 1
    默认对结构体名称进行一个 蛇形命名 的转换
    https://gorm.io/zh_CN/docs/conventions.html#%E5%A4%8D%E6%95%B0%E8%A1%A8%E5%90%8D
    如果想自定义表名,可以实现 Tabler 接口
    https://gorm.io/zh_CN/docs/conventions.html#TableName
    KotlinAmai
        3
    KotlinAmai  
       Oct 21, 2022
    也可以通过命名策略进行全局设置
    https://gorm.io/zh_CN/docs/gorm_config.html#naming_strategy
    ZhenShaw
        4
    ZhenShaw  
       Oct 21, 2022 via Android
    要么框架默认规则,要么实现表名的接口
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   5431 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 07:17 · PVG 15:17 · LAX 00:17 · JFK 03:17
    ♥ Do have faith in what you're doing.