Skip to content

Instantly share code, notes, and snippets.

@devdave
Created June 21, 2011 23:40
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save devdave/1039231 to your computer and use it in GitHub Desktop.
Save devdave/1039231 to your computer and use it in GitHub Desktop.
Semi-dynamic Doctrine2 search function
<?php
function searchCriteria($criteria){
$cleanCritera = array();
foreach($criteria as $key => $value){
if( isset( $this->_class->fieldNames[$key] ) && !empty($value) ){
$cleanCritera[$key] = $value;
}
}
if(empty($cleanCritera)){
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 other...so ->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}%");
}
$queryBuilder->where($or);
return $queryBuilder->getQuery()->getResult();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment