From 0b76a037dda7ef8979b8175d043d65de550fdb76 Mon Sep 17 00:00:00 2001 From: Michele Angioni Date: Sat, 28 Mar 2015 14:50:18 +0100 Subject: [PATCH] Added countWhereHas() query method --- README.md | 1 + .../Repos/AbstractEloquentRepository.php | 29 +++++++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/README.md b/README.md index def94e6..98cb24d 100644 --- a/README.md +++ b/README.md @@ -136,6 +136,7 @@ The `AbstractEloquentRepository` empowers automatically our repositories of the - truncate() - count() - countBy(array $where = array()) +- countWhereHas($relation, array $where = array(), array $whereHas = array()) The Repos module also supports xml repositories. Suppose we have a staff.xml file. We need to define a `StaffXMLRepositoryInterface` diff --git a/src/MicheleAngioni/Support/Repos/AbstractEloquentRepository.php b/src/MicheleAngioni/Support/Repos/AbstractEloquentRepository.php index ef9d52e..a9ec1b0 100644 --- a/src/MicheleAngioni/Support/Repos/AbstractEloquentRepository.php +++ b/src/MicheleAngioni/Support/Repos/AbstractEloquentRepository.php @@ -374,6 +374,35 @@ public function countBy(array $where = array()) return $query->count(); } + /** + * Count all results that have a required relationship with input constraints + * + * @param string $relation + * @param array $where + * @param array $whereHas + * + * @return int + */ + public function countWhereHas($relation, array $where = array(), array $whereHas = array()) + { + $query = $this->make(); + + foreach($where as $key => $value) + { + $query = $query->where($key, '=', $value); + } + + $query = $query->whereHas($relation, function($q) use($whereHas) + { + foreach($whereHas as $key => $value) + { + $q = $q->where($key, '=', $value); + } + }); + + return $query->count(); + } + // <--- INTERNALLY USED METHODS --->