douqian4411 2015-10-10 14:33
浏览 11

如何在Go中从多个表构造对象

I'm trying to find the best way to work with objects represented by multiple database tables.

For database access I wrapped sqlx with my own type and then defined some methods:

type DB struct {
    *sqlx.DB
}
func (db *DB) GetSomething(id uint32) *Something {} 
func (db *DB) AddSomething(*Something) {}

It works nice for objects that map one-to-one with single database table. I see a couple of ways to work with multi-table objects:

  1. Define methods on *DB that do selects from multiple tables and then construct an object. Save is similiar.
  2. Create a layer on top of *DB which would construct an object.
  3. Do not construct an object, use its parts.

I rather prefer number 2, but need help on how to design it in Go.

  • 写回答

1条回答 默认 最新

  • duanshang7007 2015-10-12 12:44
    关注

    If just to reduce the duplication of code each time you want User, put that somewhere that deals with users. UserService if you will, along with createUser and isUserNameAvailable. Some would go even further and create separate layer just for data retrieval and persistence (DAO layer), for me that's a bit too much of boilerplate.

    Sometimes you'll find that you probably don't need a separate method at all. You're pulling a complex report from the DB, but the only time you need it is to return via single rest endpoint. The only time you need user by username and password hash is during login - just use it in unside the login(username,password) method. In those cases, just call sqlx directly in your business methods.

    评论

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP