Skip to content

Commit 7c55811

Browse files
committed
Resolve Issue : Search REST API returns wrong total_count
1 parent 9d231d1 commit 7c55811

File tree

1 file changed

+43
-1
lines changed
  • lib/internal/Magento/Framework/Search/Adapter/Mysql

1 file changed

+43
-1
lines changed

lib/internal/Magento/Framework/Search/Adapter/Mysql/Adapter.php

Lines changed: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,16 @@ class Adapter implements AdapterInterface
4949
*/
5050
private $temporaryStorageFactory;
5151

52+
/**
53+
* Query Select Parts to be skipped when prepare query for count
54+
*
55+
* @var array
56+
*/
57+
private $countSqlSkipParts = [
58+
\Magento\Framework\DB\Select::LIMIT_COUNT => true,
59+
\Magento\Framework\DB\Select::LIMIT_OFFSET => true,
60+
];
61+
5262
/**
5363
* @param Mapper $mapper
5464
* @param ResponseFactory $responseFactory
@@ -86,7 +96,7 @@ public function query(RequestInterface $request)
8696
$response = [
8797
'documents' => $documents,
8898
'aggregations' => $aggregations,
89-
'total' => count($documents)
99+
'total' => $this->getSize($query)
90100
];
91101
return $this->responseFactory->create($response);
92102
}
@@ -115,4 +125,36 @@ private function getConnection()
115125
{
116126
return $this->resource->getConnection();
117127
}
128+
129+
/**
130+
* Get rows size
131+
*
132+
* @return int
133+
*/
134+
private function getSize($query)
135+
{
136+
$sql = $this->getSelectCountSql($query);
137+
$parentSelect = $this->getConnection()->select();
138+
$parentSelect->from(['core_select' => $sql]);
139+
$parentSelect->reset(\Magento\Framework\DB\Select::COLUMNS);
140+
$parentSelect->columns('COUNT(*)');
141+
$totalRecords = $this->getConnection()->fetchOne($parentSelect);
142+
return intval($totalRecords);
143+
}
144+
145+
/**
146+
* Reset limit and offset
147+
*
148+
* @return Select
149+
*/
150+
private function getSelectCountSql($query)
151+
{
152+
foreach ($this->countSqlSkipParts as $part => $toSkip) {
153+
if ($toSkip) {
154+
$query->reset($part);
155+
}
156+
}
157+
return $query;
158+
}
159+
118160
}

0 commit comments

Comments
 (0)