Skip to content

Instantly share code, notes, and snippets.

@wesrice
Last active August 3, 2016 15:22
Show Gist options
  • Save wesrice/5f790cd459d83f9ee79a7c3c61b7fe3e to your computer and use it in GitHub Desktop.
Save wesrice/5f790cd459d83f9ee79a7c3c61b7fe3e to your computer and use it in GitHub Desktop.
<?php
/**
* Returns the total number of elements that match a given criteria.
*
* @param ElementCriteriaModel $criteria An element criteria model that defines the parameters for the elements
* we should be counting.
*
* @return int The total number of elements that match the criteria.
*/
public function getTotalElements($criteria = null)
{
// TODO: Lots in here MySQL specific.
$query = $this->buildElementsQuery($criteria, $contentTable, $fieldColumns, true);
if ($query)
{
$query
->order('')
->offset(0)
->limit(-1)
->from('elements elements');
$elementsIdColumn = 'elements.id';
$elementsIdColumnAlias = 'elementsId';
$selectedColumns = $query->getSelect();
// Normalize with no quotes. setSelect later will properly add them back in.
$selectedColumns = str_replace('`', '', $selectedColumns);
// Guarantee we select an elements.id column
if (strpos($selectedColumns, $elementsIdColumn) === false)
{
$selectedColumns = $elementsIdColumn.', '.$selectedColumns;
}
// Replace all instances of elements.id with elementsId
$selectedColumns = str_replace($elementsIdColumn, $elementsIdColumnAlias, $selectedColumns);
// Find the position of the first occurance of elementsId
$pos = strpos($selectedColumns, $elementsIdColumnAlias);
// Make the first occurance of elementsId an alias for elements.id
if ($pos !== false) {
$selectedColumns = substr_replace($selectedColumns, $elementsIdColumn.' AS '.$elementsIdColumnAlias, $pos, strlen($elementsIdColumnAlias));
}
$query->setSelect($selectedColumns);
$masterQuery = craft()->db->createCommand();
$masterQuery->params = $query->params;
$masterQuery->from(sprintf('(%s) derivedElementsTable', $query->getText()));
$count = $masterQuery->count('derivedElementsTable.'.$elementsIdColumnAlias);
return $count;
}
else
{
return 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment