How to paginate associated records?

喜你入骨 提交于 2019-11-28 02:25:22

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
    ->findBySlug($slug_prod)
    ->contain(['Metas', 'Attachments'])
    ->first();

$categoriesQuery = $this->Products->Categories
    ->find()
    ->matching('Products', function (\Cake\ORM\Query $query) use ($product) {
        return $query->where([
            'Products.id' => $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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!