Rozbudowa naszego modelu pisanego w poprzednich lekcjach – dodanie metod min oraz max, których nazwy same się opisują. Do dzieła.
Na początku korzystając ze zwykłego PDOConnection sprawdźmy, jak wygląda nasze query:
$q = $conn->query('SELECT DISTINCT(age) FROM people ORDER BY age ASC LIMIT 1');
print_r($q->fetch()) . "<br>";
// Array ( [age] => 20 [0] => 20 )
Tak samo możemy dostać maksimum:
$q = $conn->query('SELECT DISTINCT(age) FROM people ORDER BY age DESC LIMIT 1');
print_r($q->fetch()) . "<br>";
// Array ( [age] => 30 [0] => 30 )
Można to jeszcze uprościć:
$q = $conn->query('SELECT MAX(age) FROM people');
print_r($q->fetch()) . "<br>";
// Array ( [MAX(age)] => 30 [0] => 30 )
Piszemy zatem:
abstract class Model {
protected static $conn;
const OPERATORS = ['=', '>=', '>', '<=', '<', '<>'];
//(...)
public static function min($col){
$table = static::$tablename;
if(in_array($col, static::$keys)){
$query = "SELECT MIN({$col}) FROM {$table}";
$q = static::$conn->query($query);
return $q->fetch()[0];
}
}
public static function max($col){
$table = static::$tablename;
if(in_array($col, static::$keys)){
$query = "SELECT MAX({$col}) FROM {$table}";
$q = static::$conn->query($query);
return $q->fetch()[0];
}
}
}
Ustawiamy PersonModel:
$conn = new PDOConnection();
$conn->connect();
$conn = $conn->getConnection();
class PersonModel extends Model {
protected static $tablename = 'people';
protected static $keys = ['name', 'age'];
}
$person = new PersonModel();
$person->setConn($conn);
I sprawdzamy:
echo PersonModel::min('age');
//20
echo PersonModel::max('age');
//30