2017-11-29 6 views
0

私が達成しようとしているのはかなりシンプルですが、正しい方法を理解することができません。CakePHP 3結果をページ区切り

私のデータベースにProductsテーブルがあります。各製品には多くのイメージと色があり、1つまたは複数のカテゴリに属します。

カテゴリのIDを受け取って、ページングされた商品を返します。

これは私のコードは、私が試した2つの異なるアプローチで、今のように見えるものです:

$paginatorQuery = $this->Categories->Products->find('all', [ 
     'contain' => [ 
      'Categories' => [ 
       'conditions' => [ 
        'category_id' => $categoryId 
       ] 
      ], 
      'Colors', 
      'Images' 
     ], 
     'conditions' => $conditionArray, 
     'order' => [ 
      $session->read('productSort.field') => $session->read('productSort.direction') 
     ], 
    ]); 

    $catProd = $this->Categories->get($categoryId, [ 
     'contain' => [ 
      'Products' => [ 
       'Colors', 
       'Images', 
       'conditions' => $conditionArray, 
       'sort' => [ 
        $session->read('productSort.field') => $session->read('productSort.direction') 
       ], 
      ] 
     ], 
    ]); 

    // $catProd = $catProd->products; 

    $products = $this->paginate($paginatorQuery); 

変数$paginatorQueryは(私はそれが理由かのではないことを知っていた正しくフィルタリングしません論理はありますが、ちょうどそれを試してみることに決めました)、代わりに期待されるもの(既存のすべての製品、対応するIDを持つカテゴリーに属する製品の場合は製品が含まれます)を返します。

コメント行$catProd = $catProd->productsは、変数$catProdに目的の結果セットを割り当てますが、ページングを管理することはできません。私は制限を割り当てて手動のページネーションを実装することを考えていますが、そのクエリには始まりますが、私には問題を救うために欠けているものがなければならないと思います。

ありがとうございます!

答えて

2

$paginatorQuerymatchingで、containではなく、カテゴリに使用する必要があります。このようなもの(未テスト):

$paginatorQuery = $this->Categories->Products->find('all', [ 
    'contain' => [ 
     'Colors', 
     'Images' 
    ], 
    'conditions' => $conditionArray, 
    'order' => [ 
     $session->read('productSort.field') => $session->read('productSort.direction') 
    ], 
]) 
->matching('Categories', function (Query $q) use ($categoryId) { 
    return $q->where(['Categories.id' => $categoryId]); 
}); 

詳細はfiltering by associated dataを参照してください。

+0

ありがとう、それはトリックでした。私が正しく覚えていれば、私は前にマッチングを使ってみたが、useステートメントを見逃していたので、 '$ categoryId'は定義されていなかった。 – porjolovsky

関連する問題