Is it possible to simplify getRows()
or it is fine as it is now?
protected $container;
public function __construct(ContainerInterface $container) {
$this->container = $container;
$this->em = $this->getDoctrine()->getManager();
}
/*
* @param $ntt name of the entity to fetch
* @param $cols columns to fetch
* @param $where array of data to be matched (for example array('id'=>1))
* @param $result_type type of result required. (object|array)
*/
public function getRows($ntt,$cols=array(),$where=array(),$result_type=null){
$data = 'nulllllll';
if($ntt && $where && is_array($where)){
$i = 1;
$filter = '';
foreach ($where as $key => $value) {
if(is_array($value)){
$filter = $filter.($filter ? ' AND ' : '')."tm.$key in (:v$i)";
}else{
$filter = $filter.($filter ? ' AND ' : '')."tm.$key = :v$i";
}
$param['v'.$i] = $value;
$i++;
}
$select = 'tm';
if($cols){
$select = '';
foreach ($cols as $col) {
$select = $select.($select ? ', ' : '')."tm.$col";
}
}
$ntt = 'AppBundle:'.$ntt;
$data = $this->em->getRepository($ntt)->createQueryBuilder('tm')
->select($select)
->where($filter)
->setParameters($param)
->getQuery();
if($result_type == 'array'){
$data = $data->getArrayResult();
}else{
$data = $data->getResult();
}
}
return $data;
}
Calling:
getRows('My_user',array('lName','llname'),array('id'=>array(1,4,50)),'array')
Where My_user
is my entity name and lName
and llname
are the columns I want to fetch.
Will output:
Array
(
[0] => Array
(
[lName] => Abc
[llname] => Sha
)
[1] => Array
(
[lName] => And
[llname] => Bainbri
)
[2] => Array
(
[lName] => Ken
[llname] => Lee
)
)
$query
because that is whatgetQuery()
returns. Using$data = $data->someMethod()
isn't a good practice for obvious reasons. \$\endgroup\$