php - 如何使用 Symfony2 实现搜索过滤器表单

标签 php doctrine-orm symfony-2.1

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

我在与实体关联的存储库上使用特定方法在查询中添加连接(为了避免许多查询)。 Controller 看起来像这样:

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 表单对象,其中包含多个用于搜索项目的字段。

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

这是我的 Controller 中有关搜索表单的内容:

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
           }
     }
}

谢谢!

最佳答案

这是我会尝试的:

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();
}

关于php - 如何使用 Symfony2 实现搜索过滤器表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11449840/

相关文章:

php - 如何将一些嵌套结构与正则表达式匹配?

php - 如何根据在 Google 上搜索的字词为自定义网址编制索引

download - Symfony2.1 服务上传

php - Propel,为选择语句添加别名

Symfony2 多枝扩展

php - Apache HTTP 服务器已停止在 Xampp 中工作

PHP - 字符串操作删除特殊字符并替换空格

symfony - Doctrine2 - 没有关系的子查询连接

php - Symfony 学说分页

doctrine-orm - 教义 2 - 获取所有记录