title: Cakephp 3 belongsToMany subquery searching
body: <p>I have a products table that belongsToMany Tags and Categories. The Tags and Categories also belongsToMany products. </p>
  
  <p>I am trying to implement a searching functionality that will include any products where the search parameters match tagged products, categorized products, and any product's title or description.</p>
  
  <p>This is what I have in my controller:</p>
  
  <pre><code>public function index()
  {
      $this-&gt;paginate = [
          'sortWhitelist' =&gt; [
              'Products.title',
              'Products.msrp',
              'Products.sale_price',
          ],
          'limit'   =&gt; 48,
          'order'   =&gt; ['Products.title' =&gt; 'asc']
      ];
      $products = $this-&gt;Products-&gt;find();
      if ($search = $this-&gt;request-&gt;query('search')) {
          $matchingCategories = $this-&gt;Products-&gt;find()-&gt;matching('Categories', function ($q) use ($search) {
              return $q-&gt;where(['Categories.name LIKE' =&gt; "%$search%"]);
          });
          $matchingTags = $this-&gt;Products-&gt;find()-&gt;matching('Tags', function ($q) use ($search) {
              return $q-&gt;where(['Tags.name LIKE' =&gt; "%$search%"]);
          });
          $products
              -&gt;where(['Products.title LIKE' =&gt; "%$search%"])
              -&gt;orWhere(['Products.description LIKE' =&gt; "%$search%"])
              -&gt;orWhere(['Products.id IN' =&gt; $matchingCategories])
              -&gt;orWhere(['Products.id IN' =&gt; $matchingTags]);
      }
  
      $this-&gt;set('products', $this-&gt;paginate($products));
      $this-&gt;set('_serialize', ['products']);
  }
  </code></pre>
  
  <p>You can kind of see what I am trying to accomplish here, but it obviously doesn't work. I can get any 1 part of the equation to work, meaning I can either get products with matching categories, or products with matching tags, or products with matches in their title or descriptions, but I can't get all products where the search fits in any of these parts.</p>