CakePHP 3 对结果进行分页

CakePHP 3 Paginate a result

我想要实现的目标非常简单,但我无法找出正确的方法。

我的数据库中有一个产品 table。每个产品都有很多图片和颜色,属于一个或多个类别。

我正在尝试创建一个接收类别 ID 和 returns 它包含的分页产品的操作。

这就是我的代码现在的样子,使用了我尝试过的两种不同方法:

    $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 没有正确过滤(我知道它不会因为逻辑有多么有缺陷,但决定尝试一下以防万一),而是 returns预期是什么(所有现有产品,如果产品属于具有相应 ID 的类别,则产品包含它)。

注释行 $catProd = $catProd->products 将所需结果集分配给变量 $catProd,但我无法对其进行分页。我正在考虑通过分配限制并开始该查询来实现手动分页,但我认为一定有一些我遗漏的东西可以省去我的麻烦。

谢谢!

您的 $paginatorQuery 应该在类别上使用 matching,而不是 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