title: belongsToMany with parent-child relationship in Laravel 5
body: <p>I have two models that are related to each other with a <code>belongsToMany</code> relationship. The models are <code>Game</code> and <code>Category</code>. Of course, the tables for both are <code>games</code> and <code>categories</code>. The <code>Category</code> model, has its own parent-child relationship.</p>
  
  <p>Basically this is my "simplified" structure:</p>
  
  <pre><code>Table game:
  id          unsigned integer
  name        string
  
  Table categories:
  id          unsigned integer
  name        string
  parent_id   unsigned integer nullable
  </code></pre>
  
  <p>The <code>parent_id</code> column is <code>null</code> when the category has no parent, but it has an existing id referencing a row in the same table if it is a children of some other category.</p>
  
  <pre><code>Table category_game
  category_id unsigned integer
  game_id     unsigned integer
  </code></pre>
  
  <p>The <code>category_id</code> column, references <code>id</code> on <code>categories</code> table. It should reference only the top category that a game belongs to. A game can belong to many different categories, but in the pivot table, there should only be a reference to the parents categories. For example if I had this structure of categories:</p>
  
  <pre><code>Category 1
    Category 2
      Category 4
    Category 3
      Category 9
  Category 5
    Category 6
    Category 7
      Category 8
  </code></pre>
  
  <p>I would like to have the following information for my games 1 and 2:</p>
  
  <pre><code>category_id  game_id
            3        1
            5        1
            1        2
  </code></pre>
  
  <p>And that should mean that my game 1 has categories: 3, 9, 5, 6, 7 and 8.
  While my game 2 has categories: 1, 2, 4, 3 and 9</p>
  
  <p>I understand that my Laravel models should have this:</p>
  
  <pre><code>class Game {
      public function categories(){
          return $this-&gt;belongsToMany( Category::class );
      }
  }
  
  class Category{
      public function games(){
          return $this-&gt;belongsToMany( Game::class );
      }
  }
  </code></pre>
  
  <p>But I don't know how to retrieve the children categories using Eloquent. I know the <code>belongsToMany</code> method has more parameters that might help with my problem, but I don't know how to use them.</p>