From 1bf75f787790f06b945c3fe214f0b18edc7c5fc9 Mon Sep 17 00:00:00 2001 From: Thomas Lange Date: Tue, 29 Jun 2021 21:43:30 +0200 Subject: Add WHERE filter option to getCount method --- core/namespace/ORM/Repository.php | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) (limited to 'core/namespace') diff --git a/core/namespace/ORM/Repository.php b/core/namespace/ORM/Repository.php index 1eb687d..929dae3 100644 --- a/core/namespace/ORM/Repository.php +++ b/core/namespace/ORM/Repository.php @@ -183,11 +183,30 @@ abstract class Repository { #=========================================================================== # Get entity count #=========================================================================== - public function getCount(): int { - $query = 'SELECT COUNT(id) FROM %s'; - $query = sprintf($query, static::getTableName()); + public function getCount(array $filter = []): int { + $wheres = []; + $params = []; + + if(!empty($filter)) { + foreach($filter as $column => $value) { + if($value === NULL) { + $wheres[] = "$column IS NULL"; + } else { + $wheres[] = "$column = ?"; + $params[] = $value; + } + } + + $where = 'WHERE '.implode(' AND ', $wheres); + } + + $query = 'SELECT COUNT(id) FROM %s %s'; + $query = sprintf($query, static::getTableName(), $where ?? ''); + + $Statement = $this->Database->prepare($query); + $Statement->execute($params); - return $this->Database->query($query)->fetchColumn(); + return $Statement->fetchColumn(); } #=========================================================================== -- cgit v1.2.3