diff --git a/model/SqlModel.php b/model/SqlModel.php index 2d12afe..083869f 100644 --- a/model/SqlModel.php +++ b/model/SqlModel.php @@ -15,6 +15,24 @@ */ abstract class SqlModel extends Model { + const SELECT = 10; + const DISTINCT = 11; + const WHERE = 12; + const ORDER = 13; + const ORDER_TO_DESC = 14; + const LIMIT = 15; + const OFFSET = 16; + + protected static $criteria_data_keys = array( + self::SELECT, + self::DISTINCT, + self::WHERE, + self::ORDER, +/** self::ORDER_TO_DESC, // no to be process in foreach criteria_data @see SqlModel::find() */ + self::LIMIT, +/** self::OFFSET // no to be process in foreach criteria_data @see SqlModel::find() */ + ); + /** * @param string $ident * @return string Quoted identifier. @@ -179,8 +197,9 @@ abstract class SqlModel extends Model /** * @param $criteria SqlCriteria + * @return string Sql string expression */ - public function find($criteria) + protected function criteria($criteria) { foreach ($criteria->select as $field => &$term) { if (is_int($field)) { @@ -202,10 +221,48 @@ abstract class SqlModel extends Model if ($criteria->distinct != '') { $criteria->distinct = 'DISTINCT ' . $this->db->quoteIdentifier($criteria->distinct); } - $sql = 'SELECT ' . (($criteria->distinct) ? $criteria->distinct : implode(',', $criteria->select)) + return 'SELECT ' . (($criteria->distinct) ? $criteria->distinct : implode(',', $criteria->select)) . ' FROM ' . $this->db->quoteIdentifier($this->table) . (($criteria->where) ? (' WHERE ' . implode(' AND ', $criteria->where)) : '') . (($criteria->order) ? (' ORDER BY ' . implode(',', $criteria->order)) : '') . (($criteria->limit) ? (' LIMIT ' . implode(',',array_map(function($item){return intval($item);},explode(',',$criteria->limit)))) : ''); } + + /** + * @param $criteria_data array + * @ex array( + * SqlModel::SELECT => '*', + * SqlModel::WHERE => array('field=?', 1), + * SqlModel::ORDER => array('last_name', 'first_name'), + * SqlModel::ORDER_TO_DESC => array('last_name'), + * SqlModel::LIMIT => 10) + * @return mixed|DbStatement[] + */ + public function find($criteria_data) + { + $criteria = new SqlCriteria(); + foreach (self::$criteria_data_keys as $criteria_data_key) { + if (isset($criteria_data[$criteria_data_key])) { + $value = $criteria_data[$criteria_data_key]; + switch ($criteria_data_key) { + case self::SELECT: + $criteria->select($value); + break; + case self::DISTINCT: + $criteria->distinct($value); + break; + case self::WHERE: + $criteria->where($value); + break; + case self::ORDER: + $criteria->order($value, ((isset($criteria_data[self::ORDER_TO_DESC])) ? $criteria_data[self::ORDER_TO_DESC] : null)); + break; + case self::LIMIT: + $criteria->limit($value, ((isset($criteria_data[self::OFFSET])) ? $criteria_data[self::OFFSET] : null)); + break; + } + } + } + return self::fetchAll($this->criteria($criteria)); + } } \ No newline at end of file