title: Reference two tables that are related to each other
body: <p>Imagine that I have these entities: <code>Folder</code>, <code>Group</code>, <code>Document</code>.</p>
  
  <p>Now, each <code>Folder</code> has many <code>Document</code>'s and these <code>Document</code>'s can have a <code>Group</code> or not, inside that <code>Folder</code>.</p>
  
  <p>So, a <code>Folder</code> would contain both grouped and ungrouped <code>Document</code>'s.</p>
  
  <p>How would I structure such relations?</p>
  
  <p>I was thinking of two ways:</p>
  
  <ol>
  <li><code>Document</code> belongs to <code>Group</code> and <code>Group</code> belongs to <code>Folder</code>. This
  requires me to always have an "ungrouped" <code>Group</code> for every <code>Folder</code>
  (really ugly).</li>
  <li><code>Document</code> belongs to both <code>Folder</code> and <code>Group</code>, <code>Group</code> belongs to
  <code>Folder</code>. This way I have the reference to the <code>Folder</code> and the
  <code>Group</code>, where the <code>group_id</code> can be null to represent "ungrouped".
  But this opens a door for error, by assigning a <code>Document</code> to a
  <code>Group</code>/<code>Folder</code> where the <code>Group</code> doesn't belong to that <code>Folder</code>.</li>
  </ol>
  
  <p>Neither solution seems right. This probably needs some kind of composite key and the <code>Document</code> would reference that.</p>
  
  <p>What would be the proper way of doing this?</p>