Doctrine and Symfony2: WHERE a.title LIKE $array


Doctrine and Symfony2: WHERE a.title LIKE $array

嘿,我正在写这篇文章,因为我在学说查询中传递数组值几乎没有问题。

以下是整个查询:

$data = $request->request->all();
$dql   = "SELECT a FROM PfBlogBundle:Article a WHERE a.title LIKE '{$data['search']}' ORDER by a.id DESC";

如果我print_r($data),我会得到值,所以它在某个地方。我只是不明白为什么它没有传入查询..期望像"{$data['搜索']}"一样工作,但它没有。

从我的片段可以看出,您正在寻找这样的东西:

$entityManager->getRepository('PfBlogBundle:Article')
              ->findBy(
                   array(
                      'key' => 'value'
                   )
               );

其中键是属性/字段,值是要查找的值。查看Symfony手册页。您所追求的是从数据库中获取对象。
要在 where 子句中使用like,请参阅此 SO 问题,了解如何使用 setParameter 。您将获得以下查询:

$repo = $entityManager->getRepository('PfBlogBundle:Article');
$query = $repo->createQueryBuilder('a')
               ->where('a.title LIKE :title')
               ->setParameter('title', '%'.$data['search'].'%')
               ->getQuery();

当然,添加通配符以满足您的需求。我将$data['search']值括在两个%通配符中,这很慢,但话又说回来:我不知道你实际上在做什么。可能是您所追求的只是LIKE的不区分大小写的性质,在这种情况下,%可以一起省略......

根据您之前的问题(顺便说一句:考虑偶尔接受一个答案):

public function searchAction(Request $request)
{
    $data = $request->get->all();
    $repo = $this->getDoctrine()
                  ->getRepository('PfBlogBundle:Article');
    $query = $repo->createQueryBuilder('a')
                   ->where('a.title LIKE :title')
                   ->setParameter('title', '%'.$data['search'].'%')
                   ->getQuery();
    $paginator  = $this->get('knp_paginator');
    $pagination = $paginator->paginate(
        $query->getResults(),//get the results here
        $this->requrest->get('page',1),
        4
    );
    return $this->render('PfBlogBundle:Default:blog.html.twig', array('pagination'=>$pagination));
}

但这只是一个粗略的修复,谷歌学说-symfony分页,有很多关于此事的详细博客文章