title: Laravel query builder for recursive results? E.g. id, parent_id
body: <p>So I have data structured like this:</p>
  
  <pre><code>id|parent_id|name
  1 |null     |foo
  2 |1        |bar
  3 |2        |baz
  </code></pre>
  
  <p>So basically <code>foo-&gt;bar-&gt;baz</code>. I'm stumped on how to use laravel's query builder to get rows for a child row, then its ancestors (until <code>parent_id == null</code>). Can this be done with laravel? I've done a little research and Postgres has <code>RECURSIVE</code> while MySQL doesn't (<a href="https://stackoverflow.com/questions/19386334/postgres-recursive-query-to-update-values-of-a-field-while-traversing-parent-id">Postgres recursive query to update values of a field while traversing parent_id</a>).</p>
  
  <p>I believe MySQL has something similar: <a href="https://stackoverflow.com/questions/16513418/how-to-do-the-recursive-select-query-in-mysql">How to do the Recursive SELECT query in MySQL?</a></p>
  
  <p>But how would I implement this in Laravel?</p>
  
  <p>My starting code is basically using a query scope, but I'm just not getting it right:</p>
  
  <pre><code>Model::select('name')-&gt;getParent(3); //get baz and the ancestors of baz
  protected function scopeGetParent($id) {
    $parent = Model::where('id', '=', $id);
    return $query-&gt;getParent($parent-&gt;parent_id);
  }
  </code></pre>
  
  <p>The desired result I want is:</p>
  
  <pre><code>name
  baz
  bar
  foo
  </code></pre>
  
  <p>Any ideas?</p>