问题描述
Products ownToMany Categories
和 Categories hasMany Products
,在我的 Product
视图中,我显示了所有类别的列表,但我想分页或限制这些结果.
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.
我当前在 ProductsController
上的代码是:
My current code on ProductsController
is:
$product = $this->Products
->findBySlug($slug_prod)
->contain(['Metas', 'Attachments', 'Categories'])
->first();
$this->set(compact('product'));
我知道我需要设置 $this->paginate()
来对某些内容进行分页,但我无法让它对产品内的类别进行分页.我希望你们能理解我.
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
推荐答案
分页器不支持分页关联,您必须在单独的查询中手动读取关联的记录,然后对该记录进行分页,类似的内容其中:
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'));
然后在您的视图模板中,您可以像往常一样显示您的 $product
并单独对 $categories
进行分页.
Then in your view template you can display your $product
and separately paginate $categories
as usual.
另见
这篇关于如何对关联的记录进行分页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!