How to paginate associated records?

£可爱£侵袭症+ 提交于 2019-11-26 23:42:57

问题


Products belongsToMany Categories and Categories hasMany Products, inside my Product view I'm showing a list of all it's categories but I want to paginate or limit these results.

My current code on ProductsController is:

$product = $this->Products
    ->findBySlug($slug_prod)
    ->contain(['Metas', 'Attachments', 'Categories'])
    ->first();

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

I know I need to set $this->paginate() to paginate something but I can't get it working to paginate the categories inside the product. I hope you guys can understand me.

UPDATE: Currently I have this going on:

$product = $this->Products->findBySlug($slug_prod)->contain([
              'Metas',
              'Attachments',
              'Categories' => [
                'sort' => ['Categories.title' => 'ASC'],
                'queryBuilder' => function ($q) {
                  return $q->order(['Categories.title' => 'ASC'])->limit(6);
                }
              ]
            ])->first();

The limit works but I don't know how to paginate yet


回答1:


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

  • Cookbook > Controllers > Components > Pagination
  • Cookbook > Views > Helper> Paginator
  • Cookbook > Database Access & ORM > Query Builder > Filtering by Associated Data


来源:https://stackoverflow.com/questions/43901181/how-to-paginate-associated-records

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