title: How to avoid stack overflow with gorm?
body: <p>First, database is created with <code>sqlite3 test.db &lt; schema.sql</code>.</p>
  <p>Contents of <code>schema.sql</code>:</p>
  <pre><code>CREATE TABLE x (
      id   INTEGER PRIMARY KEY,
      name TEXT
  );
  
  CREATE TABLE y (
      id   INTEGER PRIMARY KEY,
      name TEXT,
      x_id INTEGER REFERENCES x
  );
  </code></pre>
  <p>Then the program is run with <code>go run main.go</code>.</p>
  <p>Contents of <code>main.go</code>:</p>
  <pre><code>package main
  
  import (
      &quot;gorm.io/gorm&quot;
      &quot;gorm.io/driver/sqlite&quot;
  )
  
  type X struct {
      ID   uint
      Name string
      Ys   []*Y
  }
  
  type Y struct {
      ID   uint
      Name string
      X    *X     `gorm:&quot;column:x_id&quot;`
  }
  
  func (X) TableName() string {
      return &quot;x&quot;
  }
  
  func (Y) TableName() string {
      return &quot;y&quot;
  }
  
  func main() {
      db, _ := gorm.Open(sqlite.Open(&quot;test.db&quot;), &amp;gorm.Config{})
  
      x := &amp;X{Name: &quot;X&quot;}
      y := &amp;Y{Name: &quot;Y&quot;, X: x}
      x.Ys = []*Y{y}
  
      db.Create(&amp;x)
  }
  </code></pre>
  <p>After which <code>fatal error: stack overflow</code> is thrown.</p>
  <p>I guess it has something to do with the recursive nature of the structs and objects involved. When I comment out the <code>Ys []*Y</code> line along with <code>y := &amp;Y{Name: &quot;Y&quot;, X: x}</code> and <code>x.Ys = []*Y{y}</code> it successfully inserts &quot;X&quot; into table <code>x</code>, but when I comment out the <code>Ys []*Y</code> and <code>x.Ys = []*Y{y}</code> only and change <code>db.Create(&amp;x)</code> to <code>db.Create(&amp;y)</code> nothing gets inserted in either table.</p>
  <p><strong>EDIT</strong></p>
  <p>It saves <code>x</code> and <code>y</code> when <code>y := &amp;Y{Name: &quot;Y&quot;, X: x}</code> is changed to <code>y := &amp;Y{Name: &quot;Y&quot;}</code>, but with <code>x_id</code> as <code>NULL</code>.</p>