Go structs, mysql tables

agolangf · 2016-04-08 12:38:17 · 737 次点击    
这是一个分享于 2016-04-08 12:38:17 的资源,其中的信息可能已经有所发展或是发生改变。

Hello, I'm trying to map sql tables and relations to go structs. This is just for a simple side project to learn some go. I'm mapping tables directly to structs, but I'm not sure how to handle relations. I have thought of embedding struct on each side e.g.

type User struct {
    ID int
    *Organization
}

and

type Organization struct {
    ID int
    *User
}

Is this correct? or should i have another struct for each relation?

SQL would have user table, organization table and user_organization table for relation,

edit : assume its N to N identifying relation

Or am I completely off the track on this one? How would I create constructor for these?


评论:

motojo:

This should help - SQLX document to understand embedded structs: http://jmoiron.github.io/sqlx/#advancedScanning

As far as I know, you shouldn't build the relationships into the structs. Here is how I create them for MySQL:

// User table contains the information for each user
type User struct {
Id         uint32    `db:"id"`
First_name string    `db:"first_name"`
Last_name  string    `db:"last_name"`
Email      string    `db:"email"`
Password   string    `db:"password"`
Status_id  uint8     `db:"status_id"`
Created_at time.Time `db:"created_at"`
Updated_at time.Time `db:"updated_at"`
Deleted    uint8     `db:"deleted"`
}
// User_status table contains every possible user status (active/inactive)
type User_status struct {
Id         uint8     `db:"id"`
Status     string    `db:"status"`
Created_at time.Time `db:"created_at"`
Updated_at time.Time `db:"updated_at"`
Deleted    uint8     `db:"deleted"`
}
krzykizza:

thanks, it helped.


入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

737 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传