<p>gorm 的外键更多的是为了关联而非约束。</p><pre><code><p>type Profile struct { <br> ID int<br> Name string <br> User User gorm:"foreignkey:UserRefer"
</p><p> <span style="background-color: rgb(245, 245, 245);">UserRefer </span><span style="background-color: rgb(245, 245, 245);">uint</span></p><p>}</p></code></pre><p>foreignkey:UserRefer 表示将 UserRefer 和 User.ID 关联,当查询 Profile 时,可以预加载 Profile.UserRefer 对应的 User,即 Profile => User 一对一的关系<br></p><p>执行的 sql 语句类似这样</p><pre><code>select * from profile<br>select * from user where id in (UserReferer)</code></pre><p>可使用<span style="background-color: rgb(245, 245, 245); color: rgb(51, 51, 51); font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px;">db.LogMode(</span><span style="background-color: rgb(245, 245, 245); color: rgb(51, 51, 51); font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px;">true</span><span style="background-color: rgb(245, 245, 245); color: rgb(51, 51, 51); font-family: Menlo, Monaco, Consolas, "Courier New", monospace; font-size: 13px;">) 打开日志查看具体执行的 sql 语句</span></p>