如何对关联记录进行分页?
How to paginate associated records?
Products belongsToMany Categories
和 Categories hasMany Products
,在我的 Product
视图中,我显示了所有类别的列表,但我想对这些结果进行分页或限制。
我在 ProductsController
上的当前代码是:
$product = $this->Products
->findBySlug($slug_prod)
->contain(['Metas', 'Attachments', 'Categories'])
->first();
$this->set(compact('product'));
我知道我需要设置 $this->paginate()
来对某些内容进行分页,但我无法让它对产品内的类别进行分页。希望大家能理解我。
更新:目前我正在进行:
$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();
限制有效,但我还不知道如何分页
分页器不支持分页关联,您必须在单独的查询中手动读取关联记录,然后对该记录进行分页,大致如下:
$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'));
然后在您的视图模板中,您可以像往常一样显示您的 $product
并单独分页 $categories
。
另见
Products belongsToMany Categories
和 Categories hasMany Products
,在我的 Product
视图中,我显示了所有类别的列表,但我想对这些结果进行分页或限制。
我在 ProductsController
上的当前代码是:
$product = $this->Products
->findBySlug($slug_prod)
->contain(['Metas', 'Attachments', 'Categories'])
->first();
$this->set(compact('product'));
我知道我需要设置 $this->paginate()
来对某些内容进行分页,但我无法让它对产品内的类别进行分页。希望大家能理解我。
更新:目前我正在进行:
$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();
限制有效,但我还不知道如何分页
分页器不支持分页关联,您必须在单独的查询中手动读取关联记录,然后对该记录进行分页,大致如下:
$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'));
然后在您的视图模板中,您可以像往常一样显示您的 $product
并单独分页 $categories
。
另见