Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
474 views
in Technique[技术] by (71.8m points)

cakephp - How to paginate associated records?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 (CakeORMQuery $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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...