title: Laravel defining a many-to-many relationship with the same table
body: <p>So I have a <code>posts</code> table with a corresponding <code>Post</code> model. I want to have related posts for every post. Since a post can have many other related posts, it is a many-to-many relationship between the <code>posts</code> table and the <code>posts</code> table (same table).</p>
  
  <p>So I created a <code>related_posts</code> pivot table with its corresponding model <code>RelatedPost</code>. I want to define this relationship in the two models. Like so:</p>
  
  <p><strong>Post</strong> model:</p>
  
  <pre><code>public function related()
  {
   return $this-&gt;belongsToMany(RelatedPost::class, 'related_posts', 'related_id', 'post_id');
  }
  </code></pre>
  
  <p><strong>RelatedPost</strong> model:</p>
  
  <pre><code>public function posts()
  {
    return $this-&gt;belongsToMany(Post::class, 'related_posts', 'post_id', 'related_id');
  }
  </code></pre>
  
  <p>Now in my post controller after selecting a particular post, I want to get all its related posts. So I do this:</p>
  
  <pre><code>$post-&gt;related()-&gt;get();
  </code></pre>
  
  <p>But when I do this I get the following error message:</p>
  
  <blockquote>
    <p>"SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'related_posts' (SQL: select <code>related_posts</code>.*, <code>related_posts</code>.<code>related_id</code> as <code>pivot_related_id</code>, <code>related_posts</code>.<code>post_id</code> as <code>pivot_post_id</code> from <code>related_posts</code> inner join <code>related_posts</code> on <code>related_posts</code>.<code>id</code> = <code>related_posts</code>.<code>post_id</code> where <code>related_posts</code>.<code>related_id</code> = 1) "</p>
  </blockquote>
  
  <p>This is my migration for the pivot table:</p>
  
  <pre><code>  Schema::create('related_posts', function (Blueprint $table) {
        $table-&gt;increments('id');
        $table-&gt;unsignedInteger('post_id');
        $table-&gt;unsignedInteger('related_id');
        $table-&gt;timestamps();
  
        $table-&gt;foreign('post_id')-&gt;references('id')-&gt;on('posts')-&gt;onDelete('cascade');
        $table-&gt;foreign('related_id')-&gt;references('id')-&gt;('posts')-&gt;onDelete('cascade');
    });
  </code></pre>
  
  <p>I have searched all over everywhere and though the solutions I've found really make sense I haven't been able to get any of them to work.</p>
  
  <p>Any help will be very much appreciated!</p>