/** * @param ModelCriteria $criteria * @return $this|null * * Loads a model criteria. * Warning: This doesn't goodly support multi table queries. * If you need to use more than one table, use a PDO instance and * use the fetchArray() method, or select every columns you need */ public function loadModelCriteria(ModelCriteria $criteria) { $propelData = $criteria->find(); if (empty($propelData)) { return null; } $asColumns = $propelData->getFormatter()->getAsColumns(); /** * Format it correctly * After this pass, we MUST have a 2D array. * The first may be keyed with integers. */ $formattedResult = $propelData->toArray(null, false, TableMap::TYPE_COLNAME); if (count($asColumns) > 1) { /** * Request with multiple select * Apply propel aliases */ $formattedResult = $this->applyAliases($formattedResult, $asColumns); } elseif (count($asColumns) === 1) { /** * Request with one select */ $key = str_replace("\"", "", array_keys($asColumns)[0]); $formattedResult = [[$key => $formattedResult[0]]]; } $data = $this->applyAliases($formattedResult, $this->aliases); /** * Then store it */ $this->data = $data; return $this; }
/** * @return void */ protected function loadChunk() { $this->query->setOffset($this->offset); $this->query->setLimit($this->chunkSize); $this->currentDataSet = $this->query->find(); $this->offset += $this->chunkSize; }
/** * Add the search clause for an I18N column, taking care of the back/front context, as default_locale_i18n is * not defined in the backEnd I18N context. * * @param ModelCriteria $search * @param string $columnName the column to search into, such as TITLE * @param string $searchCriteria the search criteria, such as Criterial::LIKE, Criteria::EQUAL, etc. * @param string $searchTerm the searched term */ public function addSearchInI18nColumn($search, $columnName, $searchCriteria, $searchTerm) { if (!$this->getBackendContext()) { $search->where("CASE WHEN NOT ISNULL(`requested_locale_i18n`.ID)\n THEN `requested_locale_i18n`.`{$columnName}`\n ELSE `default_locale_i18n`.`{$columnName}`\n END " . $searchCriteria . " ?", $searchTerm, \PDO::PARAM_STR); } else { $search->where("`requested_locale_i18n`.`{$columnName}` {$searchCriteria} ?", $searchTerm, \PDO::PARAM_STR); } }
/** * {@inheritdoc} */ public function loadChoiceList($value = null) { if ($this->choiceList) { return $this->choiceList; } $models = iterator_to_array($this->query->find()); $this->choiceList = $this->factory->createListFromChoices($models, $value); return $this->choiceList; }
/** * Toggle visibility for an object * * @param ModelCriteria $query * @param UpdateToggleVisibilityEvent $event * * @return mixed */ public function genericToggleVisibility(ModelCriteria $query, ToggleVisibilityEvent $event) { if (null !== ($object = $query->findPk($event->getObjectId()))) { $newVisibility = !$object->getVisible(); $object->setDispatcher($event->getDispatcher())->setVisible($newVisibility)->save(); $event->setObject($object); } return $object; }
public static function addI18nCondition(ModelCriteria $query, $i18nTableName, $tableIdColumn, $i18nIdColumn, $localeColumn, $locale) { if (null === static::$defaultLocale) { static::$defaultLocale = Lang::getDefaultLanguage()->getLocale(); } $locale = static::realEscape($locale); $defaultLocale = static::realEscape(static::$defaultLocale); $query->_and()->where("CASE WHEN " . $tableIdColumn . " IN" . "(SELECT DISTINCT " . $i18nIdColumn . " " . "FROM `" . $i18nTableName . "` " . "WHERE locale={$locale}) " . "THEN " . $localeColumn . " = {$locale} " . "ELSE " . $localeColumn . " = {$defaultLocale} " . "END"); }
/** * @param ModelCriteria $search * @param $searchTerm * @param $searchCriteria */ protected function addStandardI18nSearch(&$search, $searchTerm, $searchCriteria) { foreach (self::$standardI18nSearchFields as $index => $searchInElement) { if ($index > 0) { $search->_or(); } $this->addSearchInI18nColumn($search, strtoupper($searchInElement), $searchCriteria, $searchTerm); } }
public function paginate(ModelCriteria $query, $page = 1, $maxPerPage = 25) { $queryMd5 = md5($query->toString()); $key = $query->getTableMap()->getName() . '_query_' . $queryMd5 . '_' . $page . '_' . $maxPerPage; $records = GlobalCache::get($key); if (empty($records) === true) { $records = $query->paginate($page, $maxPerPage); if ($records->isEmpty() === false) { GlobalCache::set($key, $records); } } return $records; }
public function testPreAndPostDelete() { $c = new ModelCriteria('bookstore', '\\Propel\\Tests\\Bookstore\\Book'); $books = $c->find(); $count = count($books); $book = $books->shift(); $this->con->lastAffectedRows = 0; $c = new ModelCriteriaWithPreAndPostDeleteHook('bookstore', '\\Propel\\Tests\\Bookstore\\Book', 'b'); $c->where('b.Id = ?', $book->getId()); $nbBooks = $c->delete($this->con); $this->assertEquals(12, $this->con->lastAffectedRows, 'postDelete() is called after delete() even if preDelete() returns not null'); $this->con->lastAffectedRows = 0; $c = new ModelCriteriaWithPreAndPostDeleteHook('bookstore', '\\Propel\\Tests\\Bookstore\\Book'); $nbBooks = $c->deleteAll($this->con); $this->assertEquals(12, $this->con->lastAffectedRows, 'postDelete() is called after deleteAll() even if preDelete() returns not null'); }
public static function getBackEndI18n(ModelCriteria &$search, $requestedLocale, $columns = array('TITLE', 'CHAPO', 'DESCRIPTION', 'POSTSCRIPTUM'), $foreignTable = null, $foreignKey = 'ID') { if ($foreignTable === null) { $foreignTable = $search->getTableMap()->getName(); $aliasPrefix = ''; } else { $aliasPrefix = $foreignTable . '_'; } $requestedLocaleI18nAlias = $aliasPrefix . 'requested_locale_i18n'; $requestedLocaleJoin = new Join(); $requestedLocaleJoin->addExplicitCondition($search->getTableMap()->getName(), $foreignKey, null, $foreignTable . '_i18n', 'ID', $requestedLocaleI18nAlias); $requestedLocaleJoin->setJoinType(Criteria::LEFT_JOIN); $search->addJoinObject($requestedLocaleJoin, $requestedLocaleI18nAlias)->addJoinCondition($requestedLocaleI18nAlias, '`' . $requestedLocaleI18nAlias . '`.LOCALE = ?', $requestedLocale, null, \PDO::PARAM_STR); $search->withColumn('NOT ISNULL(`' . $requestedLocaleI18nAlias . '`.`ID`)', $aliasPrefix . 'IS_TRANSLATED'); foreach ($columns as $column) { $search->withColumn('`' . $requestedLocaleI18nAlias . '`.`' . $column . '`', $aliasPrefix . 'i18n_' . $column); } }
/** * @param \Propel\Runtime\ActiveQuery\ModelCriteria $expandableQuery * @param bool $excludeDirectParent * @param bool $excludeRoot * * @return \Propel\Runtime\ActiveQuery\ModelCriteria */ public function expandQuery(ModelCriteria $expandableQuery, $excludeDirectParent = true, $excludeRoot = true) { $expandableQuery->addJoin(SpyTouchTableMap::COL_ITEM_ID, SpyProductCategoryTableMap::COL_FK_PRODUCT_ABSTRACT, Criteria::LEFT_JOIN); $expandableQuery->addJoin(SpyProductCategoryTableMap::COL_FK_CATEGORY_NODE, SpyCategoryNodeTableMap::COL_ID_CATEGORY_NODE, Criteria::INNER_JOIN); $expandableQuery->addJoin(SpyCategoryNodeTableMap::COL_FK_CATEGORY, SpyCategoryAttributeTableMap::COL_FK_CATEGORY, Criteria::INNER_JOIN); $expandableQuery = $this->categoryQueryContainer->joinCategoryQueryWithUrls($expandableQuery); $expandableQuery = $this->categoryQueryContainer->selectCategoryAttributeColumns($expandableQuery); $expandableQuery = $this->categoryQueryContainer->joinCategoryQueryWithChildrenCategories($expandableQuery); $expandableQuery = $this->categoryQueryContainer->joinLocalizedRelatedCategoryQueryWithAttributes($expandableQuery, 'categoryChildren', 'child'); $expandableQuery = $this->categoryQueryContainer->joinRelatedCategoryQueryWithUrls($expandableQuery, 'categoryChildren', 'child'); $expandableQuery = $this->categoryQueryContainer->joinCategoryQueryWithParentCategories($expandableQuery, $excludeDirectParent, $excludeRoot); $expandableQuery = $this->categoryQueryContainer->joinLocalizedRelatedCategoryQueryWithAttributes($expandableQuery, 'categoryParents', 'parent'); $expandableQuery = $this->categoryQueryContainer->joinRelatedCategoryQueryWithUrls($expandableQuery, 'categoryParents', 'parent'); $expandableQuery->withColumn('GROUP_CONCAT(DISTINCT spy_category_node.id_category_node)', 'node_id'); $expandableQuery->withColumn(SpyCategoryNodeTableMap::COL_FK_CATEGORY, 'category_id'); $expandableQuery->orderBy('depth', Criteria::DESC); $expandableQuery->orderBy('descendant_id', Criteria::DESC); $expandableQuery->groupBy('abstract_sku'); return $expandableQuery; }
public static function from($queryClassAndAlias) { list($class, $alias) = ModelCriteria::getClassAndAlias($queryClassAndAlias); $queryClass = $class . 'Query'; if (!class_exists($queryClass)) { throw new ClassNotFoundException('Cannot find a query class for ' . $class); } $query = new $queryClass(); if (null !== $alias) { $query->setModelAlias($alias); } return $query; }
public function testRequirePkReturnsModel() { // retrieve the test data $c = new ModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Book'); $testBook = $c->findOne(); $book = BookQuery::create()->requirePk($testBook->getId()); $this->assertInstanceOf(BookTableMap::OM_CLASS, $book); }
/** * @api * * @param \Propel\Runtime\ActiveQuery\ModelCriteria $expandableQuery * * @return $this */ public function joinTaxRates(ModelCriteria $expandableQuery) { $expandableQuery->addJoin(SpyTaxSetTableMap::COL_ID_TAX_SET, SpyTaxSetTaxTableMap::COL_FK_TAX_SET, Criteria::LEFT_JOIN)->addJoin(SpyTaxSetTaxTableMap::COL_FK_TAX_RATE, SpyTaxRateTableMap::COL_ID_TAX_RATE, Criteria::LEFT_JOIN); $expandableQuery->withColumn('GROUP_CONCAT(DISTINCT ' . SpyTaxRateTableMap::COL_NAME . ')', 'tax_rate_names')->withColumn('GROUP_CONCAT(DISTINCT ' . SpyTaxRateTableMap::COL_RATE . ')', 'tax_rate_rates'); return $this; }
/** * Initializes internal state of \keeko\core\model\Base\LanguageVariantQuery object. * * @param string $dbName The database name * @param string $modelName The phpName of a model, e.g. 'Book' * @param string $modelAlias The alias for the model in this query, e.g. 'b' */ public function __construct($dbName = 'keeko', $modelName = '\\keeko\\core\\model\\LanguageVariant', $modelAlias = null) { parent::__construct($dbName, $modelName, $modelAlias); }
public function replaceNames(&$clause) { return parent::replaceNames($clause); }
public function testPruneCompositeKey() { BookstoreDataPopulator::depopulate(); BookstoreDataPopulator::populate(); // save all books to make sure related objects are also saved - BookstoreDataPopulator keeps some unsaved $c = new ModelCriteria('bookstore', '\\Propel\\Tests\\Bookstore\\Book'); $books = $c->find(); foreach ($books as $book) { $book->save(); } BookTableMap::clearInstancePool(); $nbBookListRel = BookListRelQuery::create()->prune()->count(); $this->assertEquals(2, $nbBookListRel, 'prune() does nothing when passed a null object'); $testBookListRel = BookListRelQuery::create()->findOne(); $nbBookListRel = BookListRelQuery::create()->prune($testBookListRel)->count(); $this->assertEquals(1, $nbBookListRel, 'prune() removes an object from the result'); }
/** * @api * * @param \Propel\Runtime\ActiveQuery\ModelCriteria $query * * @return \Propel\Runtime\ActiveQuery\ModelCriteria */ public function queryDistinctLocalesFromQuery(ModelCriteria $query) { $query->distinct('locale_name')->withColumn(SpyLocaleTableMap::COL_ID_LOCALE, 'value')->withColumn(SpyLocaleTableMap::COL_LOCALE_NAME, 'label'); return $query; }
/** * @param ModelCriteria $search * @param PropelModelPager|null $pagination * * @return array|PropelModelPager */ protected function searchWithPagination(ModelCriteria $search, &$pagination) { $page = intval($this->getArgValue('page')); $limit = intval($this->getArgValue('limit')); $pagination = $search->paginate($page, $limit); if ($page > $pagination->getLastPage()) { return []; } else { return $pagination; } }
public function testFindOneWithClassAndColumn() { BookstoreDataPopulator::populate(); BookTableMap::clearInstancePool(); AuthorTableMap::clearInstancePool(); ReviewTableMap::clearInstancePool(); $c = new ModelCriteria('bookstore', '\\Propel\\Tests\\Bookstore\\Book'); $c->setFormatter(ModelCriteria::FORMAT_ARRAY); $c->filterByTitle('The Tin Drum'); $c->join('Propel\\Tests\\Bookstore\\Book.Author'); $c->withColumn('Author.FirstName', 'AuthorName'); $c->withColumn('Author.LastName', 'AuthorName2'); $c->with('Author'); $con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME); $book = $c->findOne($con); $this->assertEquals(array('Id', 'Title', 'ISBN', 'Price', 'PublisherId', 'AuthorId', 'Author', 'AuthorName', 'AuthorName2'), array_keys($book), 'withColumn() do not change the resulting model class'); $this->assertEquals('The Tin Drum', $book['Title']); $this->assertEquals('Gunter', $book['Author']['FirstName'], 'ArrayFormatter correctly hydrates withclass and columns'); $this->assertEquals('Gunter', $book['AuthorName'], 'ArrayFormatter adds withColumns as columns'); $this->assertEquals('Grass', $book['AuthorName2'], 'ArrayFormatter correctly hydrates all as columns'); }
/** * Performs a DELETE on the database, given a ChildGoogleshoppingProductSynchronisation or Criteria object OR a primary key value. * * @param mixed $values Criteria or ChildGoogleshoppingProductSynchronisation object or primary key or array of primary keys * which is used to create the DELETE statement * @param ConnectionInterface $con the connection to use * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows * if supported by native driver or if emulated using Propel. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ public function delete(ConnectionInterface $con = null) { if (null === $con) { $con = Propel::getServiceContainer()->getWriteConnection(GoogleshoppingProductSynchronisationTableMap::DATABASE_NAME); } $criteria = $this; // Set the correct dbName $criteria->setDbName(GoogleshoppingProductSynchronisationTableMap::DATABASE_NAME); $affectedRows = 0; // initialize var to track total num of affected rows try { // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. $con->beginTransaction(); GoogleshoppingProductSynchronisationTableMap::removeInstanceFromPool($criteria); $affectedRows += ModelCriteria::delete($con); GoogleshoppingProductSynchronisationTableMap::clearRelatedInstancePool(); $con->commit(); return $affectedRows; } catch (PropelException $e) { $con->rollBack(); throw $e; } }
public function testFindOneWithClassAndColumn() { BookstoreDataPopulator::populate(); BookTableMap::clearInstancePool(); AuthorTableMap::clearInstancePool(); ReviewTableMap::clearInstancePool(); $c = new ModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Book'); $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); $c->filterByTitle('The Tin Drum'); $c->join('Propel\\Tests\\Bookstore\\Book.Author'); $c->withColumn('Author.FirstName', 'AuthorName'); $c->withColumn('Author.LastName', 'AuthorName2'); $c->with('Author'); $c->limit(1); $con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME); $books = $c->find($con); foreach ($books as $book) { break; } $this->assertTrue($book instanceof Book, 'withColumn() do not change the resulting model class'); $this->assertEquals('The Tin Drum', $book->getTitle()); $this->assertTrue($book->getAuthor() instanceof Author, 'ObjectFormatter correctly hydrates with class'); $this->assertEquals('Gunter', $book->getAuthor()->getFirstName(), 'ObjectFormatter correctly hydrates with class'); $this->assertEquals('Gunter', $book->getVirtualColumn('AuthorName'), 'ObjectFormatter adds withColumns as virtual columns'); $this->assertEquals('Grass', $book->getVirtualColumn('AuthorName2'), 'ObjectFormatter correctly hydrates all virtual columns'); }
/** * @api * * @param \Propel\Runtime\ActiveQuery\ModelCriteria $expandableQuery * @param string $tableAlias * * @return \Propel\Runtime\ActiveQuery\ModelCriteria */ public function selectCategoryAttributeColumns(ModelCriteria $expandableQuery, $tableAlias = SpyCategoryAttributeTableMap::TABLE_NAME) { $expandableQuery->withColumn($tableAlias . '.name', 'category_name'); $expandableQuery->withColumn($tableAlias . '.meta_title', 'category_meta_title'); $expandableQuery->withColumn($tableAlias . '.meta_description', 'category_meta_description'); $expandableQuery->withColumn($tableAlias . '.meta_keywords', 'category_meta_keywords'); $expandableQuery->withColumn($tableAlias . '.category_image_name', 'category_image_name'); return $expandableQuery; }
public function __construct($dbName = 'bookstore', $modelName = 'Propel\\Tests\\Bookstore\\Author', $modelAlias = null) { parent::__construct($dbName, $modelName, $modelAlias); }
public function testFormatterWithSelect() { $c = new ModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Book'); $c->keepQuery(false); // just for this test's purpose $c->setFormatter(ModelCriteria::FORMAT_ON_DEMAND); $c->select(array('Id', 'Title')); $rows = $c->find($this->con); $this->assertTrue($c->getFormatter() instanceof \Propel\Runtime\Formatter\OnDemandFormatter, 'The formatter is preserved'); }
/** * @param ModelCriteria $query * @param RelationMap[] $relations * @param string[][] $relationFields */ public function mapToOneRelationFields(&$query, $relations, $relationFields) { if ($relations) { foreach ($relations as $name => $relation) { if ($relation->getType() != RelationMap::MANY_TO_MANY && $relation->getType() != RelationMap::ONE_TO_MANY) { $query->{'join' . $name}($name); //$query->with($name); if (isset($relationFields[$name])) { foreach ($relationFields[$name] as $col) { $query->withColumn($name . "." . $col, '"' . $name . "." . $col . '"'); } } } } } }
/** * Performs a DELETE on the database based on the current ModelCriteria * * @param ConnectionInterface $con the connection to use * @return int The number of affected rows (if supported by underlying database driver). This includes CASCADE-related rows * if supported by native driver or if emulated using Propel. * @throws PropelException Any exceptions caught during processing will be * rethrown wrapped into a PropelException. */ public function delete(ConnectionInterface $con = null) { if (null === $con) { $con = Propel::getServiceContainer()->getWriteConnection(TranslationCatalogTableMap::DATABASE_NAME); } $criteria = $this; // Set the correct dbName $criteria->setDbName(TranslationCatalogTableMap::DATABASE_NAME); // use transaction because $criteria could contain info // for more than one table or we could emulating ON DELETE CASCADE, etc. return $con->transaction(function () use($con, $criteria) { $affectedRows = 0; // initialize var to track total num of affected rows TranslationCatalogTableMap::removeInstanceFromPool($criteria); $affectedRows += ModelCriteria::delete($con); TranslationCatalogTableMap::clearRelatedInstancePool(); return $affectedRows; }); }
/** * Initializes internal state of \Tekstove\ApiBundle\Model\Acl\Base\PermissionGroupPermissionQuery object. * * @param string $dbName The database name * @param string $modelName The phpName of a model, e.g. 'Book' * @param string $modelAlias The alias for the model in this query, e.g. 'b' */ public function __construct($dbName = 'default', $modelName = '\\Tekstove\\ApiBundle\\Model\\Acl\\PermissionGroupPermission', $modelAlias = null) { parent::__construct($dbName, $modelName, $modelAlias); }
public function paginate(ModelCriteria $query, $page = 1, $maxPerPage = 25) { return $query->paginate($page, $maxPerPage); }
public function testMagicFindByObject() { $con = Propel::getServiceContainer()->getConnection(BookTableMap::DATABASE_NAME); $c = new ModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Author'); $testAuthor = $c->findOne(); $q = BookQuery::create()->findByAuthor($testAuthor); $expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.author_id=" . $testAuthor->getId()); $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXX($value) is turned into findBy(XXX, $value)'); $c = new ModelCriteria('bookstore', 'Propel\\Tests\\Bookstore\\Author'); $testAuthor = $c->findOne(); $q = BookQuery::create()->findByAuthorAndISBN($testAuthor, 1234); $expectedSQL = $this->getSql("SELECT book.id, book.title, book.isbn, book.price, book.publisher_id, book.author_id FROM book WHERE book.author_id=" . $testAuthor->getId() . " AND book.isbn=1234"); $this->assertEquals($expectedSQL, $con->getLastExecutedQuery(), 'findByXXXAndYYY($value) is turned into findBy(array(XXX, YYY), $value)'); }