title: Laravel how to join one to many relationship tables
body: <p>I am using Laravel 5.5 and I want to display list of data by joining tables that have one to many relationship.</p>
  
  <p>Currently, I do this by going through the loop and make queries to retrieve data. This way, I think, is very inefficient, because if I were to display 1000 rows of data record, I will have to go 1000 loops to append other data with one-to-many relationship.</p>
  
  <p>I am thinking to get around this problem using cache but it does not seem to solve fundamental problem.</p>
  
  <p>For more understanding I have shared tables that I want do join as below. </p>
  
  <p><strong>Post Table</strong></p>
  
  <pre><code>| id | comment_id | status |
  |----|------------|--------|
  | 1  | 1          | 0      |
  | 2  | 2          | 0      |
  | 3  | 3          | 1      |
  | 4  | 4          | 0      |
  | 5  | 5          | 1      |
  | 6  | 6          | 1      |
  </code></pre>
  
  <p><strong>Comment Table</strong></p>
  
  <pre><code>| id | order_id | content  |
  |----|----------|----------|
  | 1  | 1        | hi       |
  | 2  | 1        | hellow   |
  | 3  | 1        | yes      |
  | 4  | 1        | okay     |
  | 5  | 2        | bye      |
  | 6  | 2        | good bye |
  </code></pre>
  
  <p>If I were to join Table <code>Post</code> with Table <code>Comment</code>, because they have one to many relationship, rows would not match. How would I join these two tables to show the list of post with comments?</p>
  
  <p><strong>Sample List Controller</strong></p>
  
  <pre><code>/**
   * @param Request $request
   * @return \Illuminate\Http\JsonResponse
   */
  public function list(Request $request)
  {
      $vaildData = $request-&gt;validate([
          'comment_id' =&gt; 'numeric',
      ]);
  
      $posts = new PostModel;
      $posts-&gt;find(1);
      $displayPosts = [];
  
      foreach ( $posts-&gt;find(1)-&gt;get() as $post ) {
          $displayPosts-&gt;comments = $post-&gt;comment()-&gt;get();
      }
  
      return $displayPosts;
  }
  </code></pre>
  
  <p><strong>Post Model</strong>
      namespace App\Model\Post;</p>
  
  <pre><code>use SoftDeletes;
  use Illuminate\Database\Eloquent\Model;
  
  class Post extends Model
  {
      public function comments()
      {
          return $this-&gt;hasMany('App\Model\Post\Comment’, ‘post_id', 'id');
      }
  }
  </code></pre>