Views: 3725
Last Modified: 21.03.2022
All parameters for getList, getRow as well as others are passed jointly, executing the query and returning the result: all is done in a single call. However, there is an alternative method of query configuration and execution oversight: the object Entity\Query:
// gets data using getList
$result = BookTable::getList(array(
'select' => array('ISBN', 'TITLE', 'PUBLISH_DATE')
'filter' => array('=ID' => 1)
));
// similar method using Entity\Query
$q = new Entity\Query(BookTable::getEntity());
$q->setSelect(array('ISBN', 'TITLE', 'PUBLISH_DATE'));
$q->setFilter(array('=ID' => 1));
$result = $q->exec();
Such approach can be convenient, when you need flexibility in building a query. For example, when query parameters are not known beforehand and are software-generated, you can use a single Query object instead of several various arguments. This object accumulates query parameters:
$query = new Entity\Query(BookTable::getEntity());
attachSelect($query);
attachOthers($query);
$result = $query->exec();
function attachSelect(Entity\Query $query)
{
$query->addSelect('ID');
if (...)
{
$query->addSelect('ISBN');
}
}
function attachOthers(Entity\Query $query)
{
if (...)
{
$query->setFilter(...);
}
if (...)
{
$query->setOrder(...);
}
}
Also the Entity\Query object allows to build a query without executing it. This can be useful for executing subqueries or simply for getting query text and subsequent use:
$q = new Entity\Query(BookTable::getEntity());
$q->setSelect(array('ID'));
$q->setFilter(array('=PUBLISH_DATE' => new Type\Date('2014-12-13', 'Y-m-d')));
$sql = $q->getQuery();
file_put_contents('/tmp/today_books.sql', $sql);
// as a result, the query "SELECT ID FROM my_book WHERE PUBLISH_DATE='2014-12-31'" will be saved into file, but not executed.
Full list of Entity\Query methods for implementing options described above:
select, group:
- setSelect, setGroup - sets array with field names
- addSelect, addGroup - adds field name
- getSelect, getGroup - returns array with field names
filter:
- setFilter - sets a single- or multidimensional array with filter description
- addFilter - adds a single filter parameter with a value
- getFilter - returns current filter description
order:
- setOrder - sets array with field names and sort order
- addOrder - adds a single field with sort order
- getOrder - returns current sort description
limit/offset:
- setLimit, setOffset - sets value
- getLimit, getOffset - returns current value
runtime fields:
- registerRuntimeField - registers new temporary field for original entity
The Query Object is the key element in data retrieval; its also used inside the standard method getList. That's why re-defining getList methods is ineffective: calling a corresponding single method is OK, but with similar query directly via Query is not.