protected function check_query($scope = 'fetch') { if ($this->isset_query($scope)) { return $this; } switch ($scope) { case 'count': $this->count = $this->count_SQL ? $this->db->value($this->count_SQL) : 0; break; default: if ($this->SQL) { $result = $this->db->query($this->SQL); $objects = array(); $schema = ORM_Model::schema($this->name); $fields = array_keys($schema['fields']); if ($result) { while ($row = $result->row('assoc')) { //创建空对象进行赋值 $object = O($this->name); $object->set_data($row); $objects[$row['id']] = $object; } } $this->objects = $objects; $this->length = count($objects); $this->current_id = key($objects); } } $this->set_query($scope, TRUE); return $this; }
function save() { if ($this->_updated) { $name = $this->_object->name(); //修正表结构 $db = ORM_Model::db($name); $id = $this->_object->id; $db->query('INSERT INTO `%1$s` (`id`, `_extra`) VALUES (%2$d, "%3$s") ON DUPLICATE KEY UPDATE `_extra`="%3$s"', $name, $id, @json_encode($this->_items, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES)); $this->_updated = FALSE; } return $this; }
/** * Delete object and remove it from the Cache * * @see ORM_Model::Destroy() * @param string $id * Model primary key value */ public static function Destroy($id) { $this->_cache()->delete(static::CacheId($id)); parent::Destroy($id); }
static function factory($name, $criteria = NULL, $no_fetch = FALSE) { $class_name = $name . MODEL_SUFFIX; if (class_exists($class_name) && is_subclass_of($class_name, 'ORM_Model')) { $object = new $class_name(); } else { $object = new ORM_Model(); } $object->name($name); $object->fetch_data($criteria, $no_fetch); //Object初始化 $object->init(); return $object; }
function makeSQL() { if ($this->name) { $db = $this->db; $SQL = $db->make_ident($this->real_name($this->name)) . ' ' . $db->quote_ident($this->table); $this->finalize_join(); if ($this->join) { $SQL .= ' ' . implode(' ', array_reverse($this->join)); } if ($this->where) { $SQL .= ' WHERE ' . $this->pack_where($this->where, 'AND'); } $SQL = trim($SQL); $count_SQL = $SQL; //from_SQL在部分pseude里面使用 $this->from_SQL = $SQL; if ($this->join) { //为了保证id的唯一 $SQL .= ' GROUP BY ' . $db->make_ident($this->table, 'id'); } if ($this->order_by) { $SQL .= ' ORDER BY ' . implode(', ', $this->order_by); } else { $SQL .= ' ORDER BY ' . $db->make_ident($this->table, 'id'); } if ($this->limit) { $SQL .= ' LIMIT ' . $this->limit; } $schema = ORM_Model::schema($this->name); $fields = join(', ', array_map(function ($f) { return $this->db->make_ident($this->table, $f); }, array_keys($schema['fields']))); $this->SQL = 'SELECT ' . $fields . ' FROM ' . $SQL; $this->count_SQL = 'SELECT COUNT(DISTINCT ' . $db->make_ident($this->table, 'id') . ') FROM' . $count_SQL; $field = $db->make_ident($this->table, '%FIELD%'); //设定sum_table, 防止子查询中table相同出现冲突问题 $sum_table = 'sum' . $this->table; $this->sum_SQL = 'SELECT SUM(' . $db->make_ident($sum_table, '%FIELD%') . ') FROM (SELECT ' . $field . ' FROM ' . $SQL . ') ' . $db->make_ident($sum_table); } }