2017-01-14 23 views
1

私はbelongsToManyタグとカテゴリのproductsテーブルを持っています。タグとカテゴリもbelongsToMany製品です。Cakephp 3 belongsToManyサブクエリ検索

タグ付けされた製品、分類された製品、および製品のタイトルや説明と検索パラメータが一致する製品を含む検索機能を実装しようとしています。

public function index() 
{ 
    $this->paginate = [ 
     'sortWhitelist' => [ 
      'Products.title', 
      'Products.msrp', 
      'Products.sale_price', 
     ], 
     'limit' => 48, 
     'order' => ['Products.title' => 'asc'] 
    ]; 
    $products = $this->Products->find(); 
    if ($search = $this->request->query('search')) { 
     $matchingCategories = $this->Products->find()->matching('Categories', function ($q) use ($search) { 
      return $q->where(['Categories.name LIKE' => "%$search%"]); 
     }); 
     $matchingTags = $this->Products->find()->matching('Tags', function ($q) use ($search) { 
      return $q->where(['Tags.name LIKE' => "%$search%"]); 
     }); 
     $products 
      ->where(['Products.title LIKE' => "%$search%"]) 
      ->orWhere(['Products.description LIKE' => "%$search%"]) 
      ->orWhere(['Products.id IN' => $matchingCategories]) 
      ->orWhere(['Products.id IN' => $matchingTags]); 
    } 

    $this->set('products', $this->paginate($products)); 
    $this->set('_serialize', ['products']); 
} 

あなたが一種の私がここで達成しようとしていますかを見ることができますが、それは明らかに動作しません:

これは私が私のコントローラを持っているものです。方程式の1つの部分を動かすことができます。つまり、カテゴリが一致する商品やタグが一致する商品、またはタイトルや説明に一致する商品が表示されますが、検索に合った商品をすべて手に入れることはできませんこれらの部分のいずれかに

答えて

0

私がしなければならなかったすべては、このようなサブクエリにだけidフィールドを選択したように見えます:

$matchingCategories = $this->Products->find()->select(['Products.id'])->matching('Categories', function ($q) use ($search) { 
    return $q->where(['Categories.name LIKE' => "%$search%"]); 
}); 

注:私は、改善のための提案を開いています。

+1

まあ、あまりにも多くのオプションはありません。もう一つは 'Categories'と' Tags'を結合し、 'Products'レベルに' LIKE'条件を追加することです。あなたがより良いパフォーマンスを与えるかもしれない、あなたが悪いことを与えるかもしれない。若干異なるオプションは、 'IN'の代わりに' EXISTS'を使うことです - もう一度、パフォーマンスは良くなるかもしれないし、悪化するかもしれません。 – ndm

+0

@ndmコメントありがとうございました。私はより良いパフォーマンスを得ることができるかどうかを確認するためにそれを試してみます。 – Battousai

関連する問題