title: Laravel 5.2 Search all records but return only parent elements' data
body: <p>I made a search function that searches name and content fields of all posts in the database. Some of these posts are in relation (parents and children). I have a problem as if my search returns a hit in a child post, I would like to return only parent data (to minimise the load).</p>
  
  <p>My Post model:</p>
  
  <pre><code>public function children()
  {
      return $this-&gt;hasMany('App\Post','parent_post_id','id');
  }
  
  public function children_count()
  {
      return $this-&gt;children()
                  -&gt;selectRaw('parent_post_id, count(*) as answers')
                  -&gt;groupBy('parent_post_id');
  }
  
  public function parents()
  {
      return $this-&gt;hasOne('App\Post','id','paren_post_id');
  }
  
  public function author()
  {
      return $this-&gt;hasOne('App\User', 'id', 'user_id');
  }
  </code></pre>
  
  <p>My search query:</p>
  
  <pre><code>$posts = Post::with('children')
  -&gt;with('children_count')
  -&gt;with('author')
  -&gt;where('name','like','%'.$search_term.'%')
  -&gt;orWhere('content','like','%'.$search_term.'%')
  -&gt;orderBy('created_at','desc')
  -&gt;groupBy('id')
  -&gt;paginate(10);
  </code></pre>
  
  <p>Example: Post#1 has two children, Post#2 and Post#3. My search finds data in Post#3, now I would like it to return data of Post#1.</p>
  
  <p><strong>EDIT:</strong>
  I see that I need to explain more what exactly would I like to achieve.</p>
  
  <p>Posts table structure:</p>
  
  <ul>
  <li>id</li>
  <li>name</li>
  <li>slug</li>
  <li>content</li>
  <li>user_id</li>
  <li>parent_post_id</li>
  <li>updated_at</li>
  <li>created_at</li>
  </ul>
  
  <p>I am searching name and content fields of each post (author (user_id) is irrelevant at this point). When search finds a hit in child post (has parent_post_id set to parent's id), I only want to get parent's data (id, slug, name, content etc.)</p>
  
  <p>I was able to achieve this with:</p>
  
  <pre><code>    $posts = DB::table('posts as a')
  -&gt;leftJoin('posts as b', 'b.parent_post_id', '=', 'a.id')
  -&gt;where('a.name','like','%'.$search_term.'%')
  -&gt;orWhere('a.content','like','%'.$search_term.'%')
  -&gt;orWhere('b.name','like','%'.$search_term.'%')
  -&gt;orWhere('b.content','like','%'.$search_term.'%')
  -&gt;select('a.*')-&gt;orderBy('a.created_at','desc')-&gt;paginate(10)
  </code></pre>
  
  <p>But was then unable to successfully count all children that returned parent has. This might also give some ideas how to wrap this Laravel way</p>
  
  <p>Can anyone point me in the right direction? </p>