V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
antxiaoye
V2EX  ›  Go 编程语言

请教 Go:ent ORM 框架,分表如何操作呢?

  •  
  •   antxiaoye · 2021-11-19 19:24:42 +08:00 · 2955 次点击
    这是一个创建于 859 天前的主题,其中的信息可能已经有所发展或是发生改变。

    现在有个项目要用 Ent 做数据库操作,但是有些表做了分表,Ent 如何处理呢?总不会是每个分表 都创建一个 Schema 吧?如何能做到一个表 Schema 根据一定规则获取不同分表的数据呢?求教求教。

    10 条回复    2021-11-22 21:08:52 +08:00
    matrix1010
        1
    matrix1010  
       2021-11-19 19:33:15 +08:00
    请看这个 PR 里我的回答: https://github.com/ent/ent/pull/2020 。需要你动动手加 template ,但是如果熟悉 Ent 应该不难
    antxiaoye
        2
    antxiaoye  
    OP
       2021-11-20 17:54:04 +08:00
    @matrix1010 刚用 Ent , template 还没弄明白呢 T_T~
    matrix1010
        3
    matrix1010  
       2021-11-20 18:19:21 +08:00
    @antxiaoye 只有增加需要 template ,删改查用 s.From(table)就行
    antxiaoye
        4
    antxiaoye  
    OP
       2021-11-20 19:19:29 +08:00
    @matrix1010 有相关文档吗?哥,小弟听不懂啊~~,我也出现了“query error Error 1146: Table 'test.apple' doesn't exist”,这种问题,和你的 GitHub 里的回答一样,不知道怎么处理好。
    matrix1010
        5
    matrix1010  
       2021-11-20 19:56:09 +08:00
    client.User.Query().Where(
    func(s *sql.Selector) {
    table := sql.Table("user_table_1")
    s.From(table)
    },
    ).All(context.TODO()) 我觉得这个挺明确啊,user_table_1 是你的分表
    antxiaoye
        6
    antxiaoye  
    OP
       2021-11-20 21:47:32 +08:00
    @matrix1010 这里我确实是这么做的,但是结果却报没有字段错误,例如:“ Error 1054: Unknown column 'user.id' in 'field list' FAIL”!

    是不是 Schema 那边我使用了 Mixin 导致的?我创建了 usermixin.go 做公共 Schema ,然后为每个分表创建一个 Schema 在复用 usermixin.go 定义的字段和索引。

    老哥能否指点一下 template 是怎么实现的吗?官方文档我看得有点懵了~~
    matrix1010
        7
    matrix1010  
       2021-11-20 22:19:34 +08:00
    @antxiaoye template 要靠你自己去理解了,因为比较复杂我几句话也没法解释到让你明白。首先你要对 go 的代码生成有个概念 https://pkg.go.dev/text/template ,比如变量怎么定义,怎么引用其他的 template 。然后你要学习 Ent 的代码生成方式,比如 create 对应的就是这个: https://github.com/ent/ent/blob/master/entc/gen/template/dialect/sql/create.tmpl
    antxiaoye
        8
    antxiaoye  
    OP
       2021-11-22 16:13:47 +08:00
    @matrix1010 感谢大佬指点,我尝试和好几个办法,都不好使,最后我直接改 meta.tmpl 模板了,将常量 Table 改成变量,查询的时候直接改 Table 的值,不晓得这么做有没有副作用~~
    matrix1010
        9
    matrix1010  
       2021-11-22 16:16:04 +08:00
    @antxiaoye 你能用就行。不过要是经常要分表建议你考虑考虑要不迁移到 tidb/polardb 上。或者直接 nosql
    antxiaoye
        10
    antxiaoye  
    OP
       2021-11-22 21:08:52 +08:00 via Android
    @matrix1010 是有计划用 polardb ~
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5539 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 09:04 · PVG 17:04 · LAX 02:04 · JFK 05:04
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.