6

我有一个要在页面上显示的项目列表,上面有一个搜索表单来过滤这些项目,就像在任何常见的后端一样。问题是我不知道如何将搜索条件添加到带有连接的现有查询中......这就是我所拥有的:

我在与实体关联的存储库上使用特定方法在查询中添加连接(以避免许多查询)。控制器如下所示:

class ModelController extends Controller
{
    public function indexAction(Request $request)
    {
        // ...
        $em = $this->getDoctrine()->getManager();
        $query = $em->getRepository('AcmeDemoBundle:Item')->getList();
    }
}

存储库上的getList方法如下所示:

use Doctrine\ORM\EntityRepository;

// ...

class ItemRepository extends EntityRepository
{
    public function getList()
    {
        $queryBuilder = $this
            ->createQueryBuilder('i')
            ->innerJoin('i.brand', 'b');

        return $queryBuilder->getQuery();
    }
}

我创建了一个ItemSearchType包含多个字段的表单对象来搜索项目。

如何从搜索表单中提供的数据中轻松添加搜索条件以显示过滤的项目?

这是我的控制器中关于搜索表单的内容:

class ModelController extends Controller
{
    public function indexAction(Request $request)
    {

        // ...
        if ($request->getMethod() === 'POST') {
           $searchForm->bindRequest($request);

           if ($searchForm->isValid()) {
               $searchCriteria = $searchForm->getData();

              // Do something with this data! ...but I don't know how
           }
     }
}

谢谢!

4

2 回答 2

10

这是我会尝试的:

public function getListBy($criteria)
{
    $qb = $this->createQueryBuilder('i');

    $qb->innerJoin('i.brand', 'b');

    foreach ($criteria as $field => $value) {
        if (!$this->getClassMetadata()->hasField($field)) {
            // Make sure we only use existing fields (avoid any injection)
            continue;
        }

        $qb ->andWhere($qb->expr()->eq('i.'.$field, ':i_'.$field))
            ->setParameter('i_'.$field, $value);
    }

    return $qb->getQuery()->getResult();
}
于 2012-07-12T22:09:01.047 回答
2

Here I posted an answer for this, I use LexikFormFilterBundle filterTypes and QueryBuilder, plus a TypeGuesser I made that abstracts the filterForm creation process.

you can install both services as separate Bundles with Composer. The resulting code is cleaner

From the README, in case you don't want to navigate to github :P

/**
 * Creates a Filter form to search for Entities.
 *
 * @param AbstractType|string $formType The `generate:doctrine:form` generated Type or its FQCN.
 *
 * @return \Symfony\Component\Form\Form The filter Form
 */
private function createFilterForm($formType)
{
    $adapter = $this->get('dd_form.form_adapter');
    $form = $adapter->adaptForm(
        $formType,
        $this->generateUrl('document_search'),
        array('fieldToRemove1', 'fieldToRemove2')
    );
    return $form;
}

It's broken for SF >= 2.8 Need a fix here

于 2014-04-10T20:42:27.323 回答