首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何对相关记录进行分页?

问如何对相关记录进行分页?
EN

Stack Overflow用户
提问于 2017-05-10 19:26:51
回答 1查看 1.4K关注 0票数 1

Products belongsToMany Categories和Categories hasMany Products,在我的Product视图中,我显示了所有类别的列表,但是我想对这些结果进行分页或限制。

我在ProductsController上的当前代码是:

代码语言:javascript
复制
$product = $this->Products
    ->findBySlug($slug_prod)
    ->contain(['Metas', 'Attachments', 'Categories'])
    ->first();

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

我知道我需要设置$this->paginate()来分页,但是我无法让它对产品中的类别进行分页。我希望你们能理解我。

最新消息:目前我正在进行以下操作:

代码语言:javascript
复制
$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();

限制有效,但我还不知道如何分页

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-05-10 20:02:03

分页器不支持分页关联,您必须在一个单独的查询中手动读取相关的记录,然后按如下方式分页:

代码语言:javascript
复制
$product = $this->Products
    ->findBySlug($slug_prod)
    ->contain(['Metas', 'Attachments'])
    ->first();

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

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

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

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

然后,在视图模板中,您可以像往常一样显示$product并单独分页$categories。

另请参阅

票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/43901181

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档