title: laravel eloquent subquery same table different columns
body: <p>i am trying to re-construct a working mysql query (or something better with the same result) in laravel eloquent. My db looks like this:</p>
  <p>I have a <strong>words</strong> table with columns <strong>id</strong> and <strong>name</strong>.
  I have a pivot table called <strong>synonyms</strong> with columns <strong>id</strong>, <strong>word_id</strong> and <strong>synonym_id</strong>.</p>
  <p>The synonyms table links words together that are synonyms. It links for example a bike and cycle together. But also bike to cycle etc.</p>
  <p>I did manage to build this query in my phpstorm editor and it works:</p>
  <pre><code>select * from words
  where id in (
      select synonym_id from synonyms
      where word_id in (select id from words where name = 'bike')
  )
  or id in (
      select word_id from synonyms
      where synonym_id in (select id from words where name = 'bike')
  )
  </code></pre>
  <p>It returns a result set containing cycle, tandem, velocipede etc.</p>
  <p>I did create a &quot;word&quot; eloquent model that has these methods:</p>
  <pre><code> /**
   * Synonyms for this word
   *
   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
   */
  public function synonyms() {
      return $this-&gt;belongsToMany(Word::class, 'synonyms', 'synonym_id', 'word_id');
  }
  
  /**
   * Words that have this word as their synonym
   *
   * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
   */
  public function isSynonymFor() {
      return $this-&gt;belongsToMany(Word::class, 'synonyms', 'word_id', 'synonym_id');
  }
  </code></pre>
  <p>And now I am trying to rebuild that query in eloquent like this:</p>
  <pre><code>    $word = 'bike'; //Just for debugging purposes I hardcoded it.
      $query = Word::whereHas('isSynonymFor', function(Builder $query) use($word) {
          $query-&gt;where('name', '=', $word);
      })-&gt;orWhereHas('synonyms', function(Builder $query) use($word) {
          $query-&gt;where('name', '=', $word);
      })
  
      return $query-&gt;get();
  </code></pre>
  <p>This does not work like I want it too. It just returns a collection with &quot;bike&quot; in it and not the rest.</p>
  <p>How can I fix it?</p>