From b80ab19d7ee1d83fd3e1408487667271e4e26f54 Mon Sep 17 00:00:00 2001 From: kj Date: Sat, 11 Sep 2021 18:27:15 -0400 Subject: [PATCH] Add option for use non-optimized count. --- src/Libs/ModelMySQL.php | 41 +++++++++++++++++++++++++++-------------- 1 file changed, 27 insertions(+), 14 deletions(-) diff --git a/src/Libs/ModelMySQL.php b/src/Libs/ModelMySQL.php index 07c74b2..1b83d1e 100644 --- a/src/Libs/ModelMySQL.php +++ b/src/Libs/ModelMySQL.php @@ -628,23 +628,37 @@ 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(). + * * @return int */ - public static function count($resetQuery = true) { + public static function count($resetQuery = true, $optimized = true) { if (!$resetQuery) - $backup = [ - 'select' => static::$querySelect['select'], - 'sql_calc_found_rows' => static::$querySelect['sql_calc_found_rows'], - 'limit' => static::$querySelect['limit'], - 'orderBy' => static::$querySelect['orderBy'] - ]; + $backup = [ + 'select' => static::$querySelect['select'], + 'sql_calc_found_rows' => static::$querySelect['sql_calc_found_rows'], + 'limit' => static::$querySelect['limit'], + 'orderBy' => static::$querySelect['orderBy'] + ]; - static::$querySelect['select'] = ['1']; - static::$querySelect['sql_calc_found_rows'] = true; - static::$querySelect['limit'] = '1'; - static::$querySelect['orderBy'] = ''; + if ($optimized) { + static::$querySelect['select'] = ['1']; + static::$querySelect['sql_calc_found_rows'] = true; + static::$querySelect['limit'] = '1'; + static::$querySelect['orderBy'] = ''; - $sql = static::buildQuery($resetQuery); + $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) { static::$querySelect['select'] = $backup['select']; @@ -653,8 +667,7 @@ class ModelMySQL { static::$querySelect['orderBy'] = $backup['orderBy']; } - $result = static::query($sql)->fetch_assoc(); - return static::found_row(); + return $result; } /*