From 182635bc9c6fe0c50657c423916f901508208bda Mon Sep 17 00:00:00 2001 From: kj Date: Sat, 11 Sep 2021 19:04:54 -0400 Subject: [PATCH] - Remove option for use non-optimized count. - Add option for limit count. --- src/Libs/ModelMySQL.php | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/src/Libs/ModelMySQL.php b/src/Libs/ModelMySQL.php index 1b83d1e..5f24986 100644 --- a/src/Libs/ModelMySQL.php +++ b/src/Libs/ModelMySQL.php @@ -628,12 +628,12 @@ class ModelMySQL { * @param boolean $resetQuery * Indica si el query debe reiniciarse o no (por defecto es true). * - * @param boolean $optimized - * Indica si se usará el conteo optimizado con sql_calc_found_rows o el normal con count(). + * @param int $límite + * Establece un límite máximo a contar (útil en caso de querer optimizar en tablas muy extensas). * * @return int */ - public static function count($resetQuery = true, $optimized = true) { + public static function count($resetQuery = true, $limit = null) { if (!$resetQuery) $backup = [ 'select' => static::$querySelect['select'], @@ -642,7 +642,16 @@ class ModelMySQL { 'orderBy' => static::$querySelect['orderBy'] ]; - if ($optimized) { + if (is_numeric($limit)) { + static::$querySelect['select'] = ['1']; + static::$querySelect['sql_calc_found_rows'] = false; + static::$querySelect['limit'] = $limit; + static::$querySelect['orderBy'] = ''; + + $sql = 'SELECT COUNT(1) AS quantity FROM ('.static::buildQuery($resetQuery).') AS counted'; + $queryResult = static::query($sql)->fetch_assoc(); + $result = $queryResult['quantity']; + } else { static::$querySelect['select'] = ['1']; static::$querySelect['sql_calc_found_rows'] = true; static::$querySelect['limit'] = '1'; @@ -651,13 +660,6 @@ class ModelMySQL { $sql = static::buildQuery($resetQuery); static::query($sql); $result = static::found_row(); - } else { - static::$querySelect['select'] = ['count(1) as quantity']; - static::$querySelect['orderBy'] = ''; - - $sql = static::buildQuery($resetQuery); - $queryResult = static::query($sql)->fetch_assoc(); - $result = $queryResult['quantity']; } if (!$resetQuery) {