Reputation: 43
Currently i develop an rest-api-app with symfony2 and doctrine2. My API should has the functionality to filter the results by an querystring.
For example, the following url:
http://example.com/api/users?orderBy=username%20DESC&limit=20
I can parse the querystring with parse_str($this->getRequest()->getQueryString(), $queryString);
to an assoc array.
Is there any function that i can commit the array and doctrine selects the corresponding results? Something like $users = $this->getDoctrine()->getRepository('UserBundle:User')->findByQueryString($queryString);
Upvotes: 0
Views: 587
Reputation: 2576
As AdrienBrault said don't use parse_str
instead put this in your controller:
$orderBy = $this->get('request')->query->get('orderBy');
$limit = $this->get('request')->query->get('limit');
$rep = $this->getDoctrine()->getRepository('UserBundle:User');
$users = $rep->findLimitOrderBy($orderBy, $limit);
And inside your user repository class:
public function findLimitOrderBy($orderBy, $limit)
{
$query = $this->getEntityManager()
->createQuery('
SELECT u FROM UserBundle:User u
ORDER BY u.'.$orderBy
)
->setMaxResults($limit);
return $query->getResult();
}
Upvotes: 1
Reputation: 7745
You shouldn't use parse_str
to access the query string parameters.
You can access the ParametersBag with $request->query
. You could get an array with $request->query->all()
.
You can use the findBy
method of the repository, that accepts an array with the following format:
array(
'field' => 'value',
'field2' => 'value2',
)
So you could do
$users = $userRepository->findBy($request->query->all());
But it won't support the orderBy
parameter.
Upvotes: 0