Go structs, mysql tables

agolangf · · 673 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hello, I&#39;m trying to map sql tables and relations to go structs. This is just for a simple side project to learn some go. I&#39;m mapping tables directly to structs, but I&#39;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&#39;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:&#34;id&#34;` First_name string `db:&#34;first_name&#34;` Last_name string `db:&#34;last_name&#34;` Email string `db:&#34;email&#34;` Password string `db:&#34;password&#34;` Status_id uint8 `db:&#34;status_id&#34;` Created_at time.Time `db:&#34;created_at&#34;` Updated_at time.Time `db:&#34;updated_at&#34;` Deleted uint8 `db:&#34;deleted&#34;` } // User_status table contains every possible user status (active/inactive) type User_status struct { Id uint8 `db:&#34;id&#34;` Status string `db:&#34;status&#34;` Created_at time.Time `db:&#34;created_at&#34;` Updated_at time.Time `db:&#34;updated_at&#34;` Deleted uint8 `db:&#34;deleted&#34;` } </code></pre></pre>krzykizza: <pre><p>thanks, it helped.</p></pre>

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

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