title: Can gorm.DB automatically resolve foreign keys?
body: <p>I'm trying to use <a href="https://github.com/jinzhu/gorm" rel="nofollow noreferrer">https://github.com/jinzhu/gorm</a> to automatically map foreign keys for me but somehow either I'm doing it wrong or the library cannot do it and I'm in the wrong.</p>
  
  <p>I have the following <code>struct</code>s:</p>
  
  <pre class="lang-golang prettyprint-override"><code>type Currency struct {
    ID           uint64 `gorm:"primary_key"`
    CurrencyCode string `gorm:"size:3"`
  }
  
  type Rate struct {
    ID          uint64 `gorm:"primary_key"`
    CurrencyID  uint64
    Currency    Currency `gorm:"ForeignKey:CurrencyID"`
    Price       float64
  }
  </code></pre>
  
  <p>and the following SQL tables (<strong>edited so that currency_code is unique</strong>)</p>
  
  <pre class="lang-sql prettyprint-override"><code>CREATE TABLE `rates` (
    `id` serial PRIMARY KEY,
    `currency_id` bigint unsigned NOT NULL,
    `price` decimal(12,2) NOT NULL,
    CONSTRAINT `fk_rate_currency`
      FOREIGN KEY (currency_id) REFERENCES currencies(id)
  );
  
  CREATE TABLE `currencies` (
    `id` serial PRIMARY KEY,
    `currency_code` char(3) NOT NULL UNIQUE
  );
  </code></pre>
  
  <p>Now I thought that when I do something like this:</p>
  
  <pre class="lang-golang prettyprint-override"><code>rate := Rate{
    Currency: Currency{
      CurrencyCode: "USD",
    },
    Price: 123,
  }
  db, _  := gorm.Open("mysql", ...)
  db.Create(&amp;rate)
  </code></pre>
  
  <p>then <code>"USD"</code> would get automatically mapped to a <code>currency_id</code> but instead it inserts new <code>"USD"</code> entry in <code>currencies</code> table for every <code>db.Create(&amp;rate)</code></p>
  
  <p>Am I doing it wrong or it's the library?</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>I know that I can do it by querying the DB for currency ID</p>
  
  <pre class="lang-golang prettyprint-override"><code>curr := db.Currency{}
  db.Where("currency_code = ?", "USD").First(&amp;curr)
  // use curr with proper ID
  </code></pre>
  
  <p>but then:</p>
  
  <ul>
  <li>I have to make 2 DB calls</li>
  <li>I don't use <code>gorm</code>'s foreign key mapping feature (if there is one)</li>
  </ul>