我想要达到的目标是很简单的,但我无法找到正确的方法。
我的数据库里有一张产品表。每个产品都有许多图像和颜色,属于一个或多个类别。
我正在尝试创建一个操作,它接收一个类别的id并返回它包含的、分页的产品。
这就是我的代码现在的样子,我尝试了两种不同的方法:
$paginatorQuery = $this->Categories->Products->find('all', [
'contain' => [
'Categories' => [
'conditions' => [
'category_id' => $categoryId
]
],
'Colors',
'Images'
],
'conditions' => $conditionArray,
'order' => [
$session->read('productSort.field') => $session->read('productSort.direction')
],
]);
$catProd = $this->Categories->get($categoryId, [
'contain' => [
'Products' => [
'Colors',
'Images',
'conditions' => $conditionArray,
'sort' => [
$session->read('productSort.field') => $session->read('productSort.direction')
],
]
],
]);
// $catProd = $catProd->products;
$products = $this->paginate($paginatorQuery);变量$paginatorQuery没有正确地过滤(我知道它不会因为逻辑的缺陷而正确,但决定尝试它以以防万一),相反,它返回预期的内容(所有现有产品,如果产品属于具有相应ID的类别,则产品包含它)。
注释行$catProd = $catProd->products将所需的结果集分配给变量$catProd,但我无法将其分页。我正在考虑通过分配限制来实现手动分页,然后开始查询,但我认为一定有我缺少的东西,这将为我省去麻烦。
谢谢!
发布于 2017-11-30 02:42:38
您的$paginatorQuery应该在类别上使用matching,而不是contain。像这样的东西(未经测试):
$paginatorQuery = $this->Categories->Products->find('all', [
'contain' => [
'Colors',
'Images'
],
'conditions' => $conditionArray,
'order' => [
$session->read('productSort.field') => $session->read('productSort.direction')
],
])
->matching('Categories', function (Query $q) use ($categoryId) {
return $q->where(['Categories.id' => $categoryId]);
});有关更多详细信息,请参阅关联数据过滤。
https://stackoverflow.com/questions/47555761
复制相似问题