How to paginate associated records?

The paginator doesn’t support paginating associations, you’ll have to read the associated records manually in a separate query, and paginate that one, something along the lines of this:

$product = $this->Products
    ->contain(['Metas', 'Attachments'])

$categoriesQuery = $this->Products->Categories
    ->innerJoinWith('Products', function (\Cake\ORM\Query $query) use ($product) {
        return $query->where([
            '' => $product->id,

$paginationOptions = [
    'limit' => 6,
    'order' => [
        'Categories.title' => 'ASC'

$categories = $this->paginate($categoriesQuery, $paginationOptions);

$this->set(compact('product', 'categories'));

Then in your view template you can display your $product and separately paginate $categories as usual.

See also

Leave a Comment