0

我正在尝试执行一个简单的查询,但我不明白我的错误在哪里。请帮忙!

这是在存储库类中:

public function searchFriends ($param)
    {
         return $this->getEntityManager()
            ->createQuery('SELECT f FROM EMMyFriendsBundle:Friend f WHERE f.name='.$param)
            ->getResult();
    }

这就是我从控制器的操作中调用它的方式:

 $em = $this->getDoctrine()->getEntityManager();
 $result = $em->getRepository('EMMyFriendsBundle:Friend')
              ->searchFriends($search->getWords()); 

当它以这种方式时,我收到以下错误:

[Semantical Error] line 0, col 54 near 'Maria': Error: 'Maria' is not defined.
500 Internal Server Error - QueryException

我试图以这种方式将搜索到的值放在引号中:

public function searchFriends ($param)
    {
         return $this->getEntityManager()
            ->createQuery('SELECT f FROM EMMyFriendsBundle:Friend f WHERE f.name=" '.$param ' " ')
            ->getResult();
    }

但后来我得到

[Syntax Error] line 0, col 59: Error: Expected end of string, got ' " '
500 Internal Server Error - QueryException

您能告诉我如何正确编写查询吗?提前致谢!


编辑

我也试过这个:

public function searchFriends ($param)
{
     $q = $this
        ->createQueryBuilder('f')
        ->where('f.name = :name')
        ->setParameter('name', $param)
        ->getQuery();

     return $q->getResult();
}

有了这个:

 $em = $this->getDoctrine()->getEntityManager();
 $result = $em->getRepository('EMMyFriendsBundle:Friend')
              ->searchFriends($search->getWords());

它正在工作

4

2 回答 2

2

虽然我不会使用这种将参数传递给查询的方式(检查这个),但您的错误在于您构建缺少点的字符串的方式。它应该是这样的:

public function searchFriends ($param)
    {
         return $this->getEntityManager()
            ->createQuery('SELECT f FROM EMMyFriendsBundle:Friend f WHERE f.name="'.$param.'"')
            ->getResult();
    }
于 2012-09-11T10:10:30.097 回答
1

您需要使用文字表达式:

public function searchFriends($param)
{
    $qb = $this->createQueryBuilder('f')
        ->where($qb->expr()->eq('f.name', $qb->expr()->literal($param)));

    return $qb->getQuery()->getResult();
}
于 2015-05-29T08:48:26.300 回答