Wondering the best way to go about querying the database with optional parameters. For example, I have a search which has name, location, price, sort by * etc
What should I do on the model and controller level on an application (I'm using Symfony2 btw)?
My thought was to dynamically build the DQL in the model, and pass serialized parameters to that via the controller like:
#controller
$res = $repo->search($serializedData);
#model/repo->search()
$data = expand($serializedData);
$dql = '';
if($data['sortby'])
$dql .= .....
Any advice?
This code is for demonstration purposes. It is not in the slight bit valid :)
In short use Doctrine 2 query builder.
The longer answer would be
#Controller
// Say if the data was a form submission
$result = $repo->search($form_data)
Then in your model you check the form array for potential keys to sort by. For example if you were searching some articles.
#Article Repository
public function search($form_data)
{
$qb = $this->getEntityManager()->createQueryBuilder();
$qb->select('Article')
->from('SomeBundle:Article');
if($form_data['title'])
{
$qb->where($qb->expr()->like('Article.title', $qb->expr()->literal('%'.$form_data['title'].'%');
}
//For subsequent filters use $qb->andWhere()
// You could do more here like pagination, or different hydration (return object or array)
return $qb->getQuery()->getResult();
}
Check out the documentation I linked to for further information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With