title: GORM Recursive Preloading
body: <p>Using Go 1.10, and CockroachDB via the Postgres <code>pq</code> driver.</p>
  
  <p>I have a GORM model that looks like this: </p>
  
  <pre><code>type User struct {
      ID            string       `gorm:"type:UUID;primary_key;NOT_NULL"`
      UserName      string
      ... &lt;other misc things here&gt;
      EnclosedUsers []User    `gorm:"many2many:enclosed_user;jointable_foreignkey:parent_id;association_jointable_foreignkey:child_id"`
  }
  </code></pre>
  
  <p>where <code>ecnlosed_user</code> is (specifically defined because reasons :) )</p>
  
  <pre><code>type EnclosedUsers struct {
      ParentID string `gorm:"type:UUID;default:'00000000-0000-0000-0000-000000000000'"`
      ChildID  string `gorm:"type:UUID;default:'00000000-0000-0000-0000-000000000000'"`
  }
  </code></pre>
  
  <p>That is, each user can have 0 or many enclosed users, and each user may have many parent users. Im trying to <code>preload</code> all of the enclosed users for each user, however GORM only preloads the first level.</p>
  
  <p>i.e.:</p>
  
  <pre><code>usr1
     |-&gt; usr 2
     |     |-&gt;usr3
     |
     |-&gt; usr4
           |-&gt;usr6
  
   usr5
     |-&gt;usr7
  </code></pre>
  
  <p>The only users that are loaded are usr1, usr2, usr4, usr5, and usr7. usr3 or usr 6 aren't. Im currently trying to recursively force the enclosed users to load with an <code>AfterFind</code> callback: </p>
  
  <pre><code>func (u *User) AfterFind(scope *gorm.Scope, role *CRRole) error {
      var childUsers []User
  
      if err := scope.DB().Model(&amp;u).Related(&amp;childUsers, "EnclosedUsers").Error; err != nil {
          return err
      }
      role.EnclosedRoles = childRoles
  
      return nil
  }
  </code></pre>
  
  <p>However this generates the following SQL: </p>
  
  <pre><code>SELECT "users".* FROM "users" INNER JOIN "enclosed_users" ON "enclosed_users"."child_id" = "enclosed_users"."id" WHERE (user_name = 'test user 1') AND ("enclosed_users"."parent_id" IN ('&lt;UUID HERE&gt;')) 
  </code></pre>
  
  <p>if the <code>user_name = ...</code> wasn't there, the query would work perfectly. </p>
  
  <p>Any ideas would be greatly appreciated.</p>