From 4394857949ce8004fbf81c819f1e774cadad9b3f Mon Sep 17 00:00:00 2001
From: Camil Staps
Date: Mon, 1 Aug 2016 14:03:44 +0200
Subject: Use Model::search in child::get* methods

---
 classes/Model.php | 29 ++++++++++++++++++++++++-----
 1 file changed, 24 insertions(+), 5 deletions(-)

(limited to 'classes/Model.php')

diff --git a/classes/Model.php b/classes/Model.php
index 4417074..0cd1fd6 100644
--- a/classes/Model.php
+++ b/classes/Model.php
@@ -154,6 +154,28 @@ abstract class Model {
 		return new $class($pdo, $pdo->lastInsertId());
 	}
 
+	/**
+	 * 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
 	 *
@@ -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;
 	}
-- 
cgit v1.2.3