diff options
author | Camil Staps | 2016-08-01 14:03:44 +0200 |
---|---|---|
committer | Camil Staps | 2016-08-01 14:03:44 +0200 |
commit | 4394857949ce8004fbf81c819f1e774cadad9b3f (patch) | |
tree | c8450147fd727d48177f85f4e712042b06e7df01 /classes/Model.php | |
parent | Makefile dependencies (diff) |
Use Model::search in child::get* methods
Diffstat (limited to 'classes/Model.php')
-rw-r--r-- | classes/Model.php | 29 |
1 files changed, 24 insertions, 5 deletions
diff --git a/classes/Model.php b/classes/Model.php index 4417074..0cd1fd6 100644 --- a/classes/Model.php +++ b/classes/Model.php @@ -155,6 +155,28 @@ abstract class Model { } /** + * Search for rows, return only ids + * + * @param PDO $pdo Database connection + * @param string[] $where Where clauses, to be ANDed + * @param mixed[] $values Variables to bind to the where clauses + * + * @throws PDOException Database error + * + * @return int[] Array of ids + */ + public static function searchIds($pdo, $where = [], $values = []) { + $stmt = $pdo->prepare("SELECT `id` FROM `".static::table()."`" . ((count($where) > 0) ? (" WHERE (" . implode(') AND (', $where) . ")") : "")); + $stmt->execute($values); + + $ids = []; + foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { + $ids[] = $row['id']; + } + return $ids; + } + + /** * Search for rows * * @param PDO $pdo Database connection @@ -168,12 +190,9 @@ abstract class Model { public static function search($pdo, $where = [], $values = []) { $class = get_called_class(); - $stmt = $pdo->prepare("SELECT `id` FROM `".static::table()."`" . ((count($where) > 0) ? (" WHERE (" . implode(') AND (', $where) . ")") : "")); - $stmt->execute($values); - $items = []; - foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) { - $items[] = new $class($pdo, $row['id']); + foreach (self::searchIds($pdo, $where, $values) as $id) { + $items[] = new $class($pdo, $id); } return $items; } |