<p>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. </p>
<pre><code>type User struct {
ID int
*Organization
}
</code></pre>
<p>and</p>
<pre><code>type Organization struct {
ID int
*User
}
</code></pre>
<p>Is this correct? or should i have another struct for each relation?</p>
<p>SQL would have user table, organization table and user_organization table for relation, </p>
<p>edit : <strong>assume its N to N identifying relation</strong></p>
<p>Or am I completely off the track on this one?
How would I create constructor for these?</p>
<hr/>**评论:**<br/><br/>motojo: <pre><p>This should help - SQLX document to understand embedded structs: <a href="http://jmoiron.github.io/sqlx/#advancedScanning" rel="nofollow">http://jmoiron.github.io/sqlx/#advancedScanning</a></p>
<p>As far as I know, you shouldn't build the relationships into the structs. Here is how I create them for MySQL:</p>
<pre><code>// 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"`
}
</code></pre></pre>krzykizza: <pre><p>thanks, it helped.</p></pre>
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889
- 请尽量让自己的回复能够对别人有帮助
- 支持 Markdown 格式, **粗体**、~~删除线~~、
`单行代码`
- 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
- 图片支持拖拽、截图粘贴等方式上传