Wednesday, 21 August 2013

Get key value list from Doctrine

Get key value list from Doctrine

I wrote this function inside my Repository class to receive a simple key
value from Doctrine. Isn't there a build in Doctrine function to do this?
(I couldn't find it). Or maybe the code can be improved.
Here's my function:
public function getListBy($criteria=null, $key, $value) {
$dql = "SELECT i.".$key." as k,
i.".$value." as v
FROM MbFooBundle:Input i";
if (isset($criteria) && is_array($criteria)) {
foreach($criteria as $cKey => $cValue) {
if (!isset($where))
$where = " WHERE ";
else
$where .= " AND ";
$where .= "i.".$cKey." = ".(is_numeric($cValue) ? $cValue :
"'".$cValue."'");
}
$dql .= $where;
}
$query = $this->getEntityManager()
->createQuery($dql);
$result = $query->getArrayResult();
$list = array();
if (count($result)) {
foreach($result as $data) {
$list[$data['k']] = $data['v'];
}
}
return $list;
}

No comments:

Post a Comment