private function createQuery($parram) { if ($this->stop) { return $parram != 2 ? array() : 0; } // Добавляем ID родителя в результаты выборки, если работаем со страницами if ($this->find_page && !$this->relsToField) { if (!strpos('link_.&..r_children_id = obj_.&..o_id', $this->where)) { $this->tables[', <<rels>> link_.&.'] = 1; $this->where .= ' and link_.&..r_children_id = obj_.&..o_id and link_.&..r_field_id is NULL '; $this->relsToField = true; } } if (!empty($this->class)) { $sn = $this->class->getSName(); } else { $sn = 'obj'; } // +++ Формируем блок SELECT +++ // Делаем специальное преобразование if (count($this->class_list) == 1 && !empty($this->fields)) { while (list($key, $val) = each($this->fields)) { $this->where = str_replace('%field_' . $val['f_sname'] . '_repl%', $val['f_id'], $this->where); } } // Формируем список полей. Попутно перепроверяем, какие контентные таблицы нам нужны //$this->isset_page_field = $this->isset_base_field = false; if (empty($this->sel_fields)) { // Выбираем все поля $this->checkFieldList(2); reset($this->fields); while (list($key, $val) = each($this->fields)) { $this->addFieldToSelect($val['f_sname'], $val['f_type'], $sn, $parram != 2); } } else { // Выбираем только указанные пользователем поля $this->sel_fields = str_replace(' ', '', $this->sel_fields); $mas = explode(',', $this->sel_fields); if ($parram != 2) { $this->sel_fields = ''; } foreach ($mas as $val) { if ($this->issetField($val)) { $type = isset($this->fields[$val]) ? $this->fields[$val]['f_type'] : 0; $this->addFieldToSelect($val, $type, $sn, $parram != 2); } } if (!empty($this->orderField)) { $type = isset($this->fields[$this->orderField]) ? $this->fields[$this->orderField]['f_type'] : 0; $this->addFieldToSelect($this->orderField, $type, $sn, $parram != 2); } } // Формируем список полей в зависимости от типа запроса: получение количества или выборки if ($parram < 2) { $rels_f = $this->relsToField ? ', link_' . $sn . '.r_position r_position, link_' . $sn . '.r_parent_id r_parent_id' : ''; if ($this->find_page) { $page_field = ', pt_' . $sn . '.other_link other_link, pt_' . $sn . '.pseudo_url pseudo_url, pt_' . $sn . '.in_new_window in_new_window, pt_' . $sn . '.is_home_page is_home_page, pt_' . $sn . '.lang_id lang_id, pt_' . $sn . '.domain_id domain_id, pt_' . $sn . '.template_id template_id, pt_' . $sn . '.template2_id template2_id'; if ($this->permission) { $page_field .= ', MAX(r_state) r_state'; } } else { $page_field = ''; } $select = '/* list */ SELECT obj_' . $sn . '.o_id o_id, obj_' . $sn . '.o_name o_name, obj_' . $sn . '.o_class_id o_class_id, obj_' . $sn . '.o_create_date o_create_date, obj_' . $sn . '.o_change_date o_change_date' . $page_field . $rels_f . ' ' . $this->sel_fields . ' '; } else { $select = '/* count */ SELECT obj_' . $sn . '.o_id id'; } // +++ Формируем блок FROM +++ // Cписок используемых таблиц $tables = ''; reset($this->tables); while (list($key, $val) = each($this->tables)) { $tables .= $key; } // Устанавливаем условие на выборку с учетом прав доступа if ($this->find_page && $this->permission) { $rights_where = str_replace('GROUP BY o_id', '', ormPages::getSqlForRights()); $tables .= ', <<rights>>'; } else { $rights_where = ''; } // +++ Собираем основную часть запроса +++ reset($this->class_list); if ($this->isset_base_field && count($this->class_list) > 1) { // Работаем с несколькими типами данных $sql = ''; $num = 0; while (list($id, $sname) = each($this->class_list)) { $num++; $union = $num >= 2 ? ' UNION ' : ''; $sql .= $union . '(' . $this->getBasePartQuery($sn, $select, $tables, $rights_where, $id, $sname) . ')'; } } else { // Работаем с одним типом данных или без выборки из таблицы данных if (count($this->class_list) && $this->isset_base_field) { list($id, $sname) = each($this->class_list); } else { $id = $sname = ''; } $sql = $this->getBasePartQuery($sn, $select, $tables, $rights_where, $id, $sname); } // Добавляем сортировку и лимит, получаем результат if ($parram != 2) { if (!empty($this->orderBy)) { $sql .= ' ' . $this->orderBy; } // else //$sql .= 'ORDER BY r_position ASC'; if (!empty($this->limit)) { $sql .= ' ' . $this->limit; } // echo $sql.'<br/><br/>'; $obj = db::q($sql, records, 0); } else { $obj = count(db::q($sql, records, 0)); } return $obj; }
/** * @return null * @param integer $obj_id - ID объекта, если не указан - дальнейшая работа в режиме добавления. * @param boolean $with_rights - Если TRUE, будут учитываться права текущего пользователя. * @desc Создание объекта и получение данных. */ public function __construct($obj_id = 0, $with_rights = true) { if (!empty($obj_id) && is_numeric($obj_id)) { $obj_id = system::checkVar($obj_id, isInt); if ($with_rights) { $where = ormPages::getSqlForRights(); $table = ', <<rights>>'; $select = ', MAX(r_state) r_state'; } else { $where = $table = $select = ''; } $sql = 'SELECT *' . $select . ' FROM <<objects>>, <<pages>>' . $table . ' WHERE o_id = "' . $obj_id . '" and p_obj_id = o_id' . $where . ';'; $row = db::q($sql, record); if ($row !== false && !empty($row)) { $this->class = ormClasses::get($row['o_class_id']); if ($this->class->isPage()) { $this->id = $obj_id; $this->name = $row['o_name']; $this->create_date = $row['o_create_date']; $this->change_date = $row['o_change_date']; $this->to_trash = $row['o_to_trash']; $this->right_state = isset($row['r_state']) ? $row['r_state'] : 0; // Информация о странице while (list($key, $val) = each($row)) { if (in_array($key, $this->page_fields)) { $this->cur_prop[$key] = $val; } } } else { $this->newError(44, 'Вы пытаетесь загрузить обычный объект с ID = ' . $obj_id . '. Используйте для этого ormObjects::get();!'); } } else { $this->newError(45, 'Невозможно загрузить данные ORM-страницы!'); } } else { if (is_array($obj_id) && isset($obj_id['o_id']) && isset($obj_id['o_class_id'])) { /* Загрузка данных в объект из другого источника (ormSelect::getObject(), ormPageCollection::getPageOfSection()). Используется для уменьшения дублирующих запросов, например при выборке объектов одного класса. */ $this->id = system::checkVar($obj_id['o_id'], isInt); $this->class = ormClasses::get($obj_id['o_class_id']); if ($this->class->isPage()) { if (isset($obj_id['o_name'])) { $this->name = system::checkVar($obj_id['o_name'], isString); } if (isset($obj_id['o_create_date'])) { $this->create_date = $obj_id['o_create_date']; } if (isset($obj_id['o_change_date'])) { $this->change_date = $obj_id['o_change_date']; } if (isset($obj_id['o_to_trash'])) { $this->to_trash = $obj_id['o_to_trash']; } if (isset($obj_id['r_state'])) { $this->right_state = $obj_id['r_state']; } // Установка значений основных полей $this->loadFields(); while (list($key, $field) = each($this->fields)) { if ($field['f_type'] > 1 && $field['f_type'] < 90) { $this->cur_prop[$key] = isset($obj_id[$key]) ? $obj_id[$key] : $this->empty; } } // Информация о странице while (list($key, $val) = each($obj_id)) { if (in_array($key, $this->page_fields)) { $this->cur_prop[$key] = $val; } } } else { $this->newError(44, 'Вы пытаетесь загрузить обычный объект с ID = ' . $obj_id['o_id'] . '. Используйте для этого ormObjects::get();!'); } } } }