title: Models and Pivot Tables
body: <p>I have a custom written solution, which I'm porting over to Phalcon. This is my first run with Phalcon, and, though it's easy to use and well documented, I can't seem to find anything about linking models that are linked through a pivot table.</p>
  
  <p>Here's the run down:</p>
  
  <p>I have users. Users have stats. The two are linked with a table called users_stats. The table contains two columns: a user ID and a stat ID. I created a third class called Users_Stats to model after the pivot table.</p>
  
  <p>User Model:</p>
  
  <pre><code>&lt;?php
  class Users extends \Phalcon\Mvc\Model {
      public function initialize() {
          $this-&gt;hasMany('stat_id', 'Users_Stats', 'user_id', array('foreignKey' =&gt; true));
      }
  }
  </code></pre>
  
  <p>Stats Model:</p>
  
  <pre><code>&lt;?php
  class Stats extends \Phalcon\Mvc\Model {
      public function initialize() {
          $this-&gt;belongsTo('stat_id', 'Users_Stats', 'id');
      }
  }
  </code></pre>
  
  <p>Users_Stats Model:</p>
  
  <pre><code>&lt;?php
  class Users_Stats extends \Phalcon\Mvc\Model {
      public function initialize() {
          $this-&gt;hasMany('user_id', 'Users', 'id');
          $this-&gt;hasMany('stat_id', 'Stats', 'id');
      }
  }
  </code></pre>
  
  <p>I just want to be able to gather the stats based on users. I am not sure if all I'm missing is that each of the models needs to belong and hasMany (Stats has many User_Stats &amp;&amp; User_Stats has many Stat; etc.). I know I'm missing something though.</p>
  
  <p>Any help would be appreciated! Thanks!</p>