Symfony – complex doctrine2 query with optional parameters

I want to know the best way to query the database with optional parameters For example, I have a search, its name, location, price, sort, etc*

What should I do at the model and controller level of the application (I use symfony2 btw)?

My idea is to dynamically build DQL in the model and pass serialization parameters to it through the controller, such as:

#controller

$res = $repo->search($serializedData);

#model/repo->search()

$data = expand($serializedData);
$dql = '';

if($data['sortby'])
  $dql .= .....

Any suggestions?

This code is for demonstration purposes It's not a little effective:)

Solution

In short, use doctrine 2 query builder

The answer will be longer

#Controller
// Say if the data was a form submission
$result = $repo->search($form_data)

Then check the form array in your model for possible sort keys For example, if you are searching for 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();
}

See my linked documents for more information

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>