Skip to content

Instantly share code, notes, and snippets.

Created June 21, 2011 23:40
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
Semi-dynamic Doctrine2 search function
function searchCriteria($criteria){
$cleanCritera = array();
foreach($criteria as $key => $value){
if( isset( $this->_class->fieldNames[$key] ) && !empty($value) ){
$cleanCritera[$key] = $value;
return null;
$queryBuilder = $this->_em->createQueryBuilder();
*@note example of partial requests, loads up a graph of Student proxies, if you ask for a field outside of the select
*criteria, Doctrine2 will make a SQL query for that specific entity.
$entityAlias = "srcEnt";
$queryBuilder->select("partial {$entityAlias}.{id, /REDACTED/, name_last, name_first, name_middle}")->from("{$this->_class->name}", $entityAlias );
//andx is used to build a WHERE clause like (expression 1 AND expression 2)
//Alternatively you can use orx for (expression 1 OR expression 2)
//Also you can next either inside of each ->where(andx(orx("expression1","expression2),"expression3"))
//would be WHERE ( ( expression 1 OR expression 2 ) AND expression 3 )
$or = $queryBuilder->expr()->andx();
*@note Example of programmatic Doctrine2 Like expression
foreach($cleanCritera as $key => $value){
$or->add($queryBuilder->expr()->like("{$entityAlias}.{$key}", ":{$key}" ));
$queryBuilder->setParameter($key, "%{$value}%");
return $queryBuilder->getQuery()->getResult();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment