Gorm and Relations

agolangf · · 499 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>Hi folks. Back-end web dev question here. Let&#39;s take a model like this: </p> <pre><code>type Allocation struct { gorm.Model ContractID uint `json:&#34;contract_id&#34; form:&#34;contract_id&#34;` Contract Contract } </code></pre> <p>And let&#39;s say the Contract looks like this: </p> <pre><code>type Contract struct { gorm.Model Variables Variables VariablesID uint `gorm:&#34;type:integer;not null&#34; json:&#34;variables_id&#34; form:&#34;variables_id&#34;` Allocations []Allocation } </code></pre> <p>I want to load my Contract, so I do it like so, correct?</p> <pre><code>connect.DB.Model(a).Related(&amp;a.Contract) </code></pre> <p>Now my a.Contract has a contract loaded in. What if I also want my Contract&#39;s Variables? </p> <pre><code>connect.DB.Model(&amp;a.Contract).Related(&amp;a.Contract.Variables) </code></pre> <p>And on and on for however long the chain of relations goes. Feels like I&#39;m doing it wrong. Do you add a method on your models to load in all the relations when you get one from the DB, or am I doing it how you do it? If this is how you do it, where do you put this logic? Load up the models in the controllers first, or...?</p> <hr/>**评论:**<br/><br/>[deleted]: <pre><p>You should use <a href="http://jinzhu.me/gorm/crud.html#preloading-eager-loading" rel="nofollow">Preload</a></p> <pre><code>err := DB. Where(&#34;foo = ?&#34;, &#34;bar&#34;). Preload(&#34;Allocations&#34;). Find(&amp;contract). Error </code></pre></pre>diabetesjones: <pre><p>Thank you very much!</p></pre>

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

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