antxiaoye
V2EX  ›  Go 编程语言

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

By antxiaoye at 2021 年 11 月 19 日 · 4592 次点击

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

10 条回复  •  2021-11-22 21:08:52 +08:00
matrix1010
   1
matrix1010  
   2021 年 11 月 19 日
请看这个 PR 里我的回答: https://github.com/ent/ent/pull/2020 。需要你动动手加 template ,但是如果熟悉 Ent 应该不难
antxiaoye
   2
antxiaoye  
OP
   2021 年 11 月 20 日
@matrix1010 刚用 Ent , template 还没弄明白呢 T_T~
matrix1010
   3
matrix1010  
   2021 年 11 月 20 日
@antxiaoye 只有增加需要 template ,删改查用 s.From(table)就行
antxiaoye
   4
antxiaoye  
OP
   2021 年 11 月 20 日
@matrix1010 有相关文档吗?哥,小弟听不懂啊~~,我也出现了“query error Error 1146: Table 'test.apple' doesn't exist”,这种问题,和你的 GitHub 里的回答一样,不知道怎么处理好。
matrix1010
   5
matrix1010  
   2021 年 11 月 20 日
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 日
@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 日
@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 日
@matrix1010 感谢大佬指点,我尝试和好几个办法,都不好使,最后我直接改 meta.tmpl 模板了,将常量 Table 改成变量,查询的时候直接改 Table 的值,不晓得这么做有没有副作用~~
matrix1010
   9
matrix1010  
   2021 年 11 月 22 日
@antxiaoye 你能用就行。不过要是经常要分表建议你考虑考虑要不迁移到 tidb/polardb 上。或者直接 nosql
antxiaoye
   10
antxiaoye  
OP
   2021 年 11 月 22 日 via Android
@matrix1010 是有计划用 polardb ~
The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
© 2026 V2EX · 60ms · 3.9.8.5