如何在Symfony2中进行LIKE数据库查询

时间:2011-09-11 16:41:29

标签: symfony doctrine-orm doctrine query-builder dql

这应该很简单,但我找不到一个有效的例子。这是一个控制器方法,它抛出错误“无效的参数号:绑定变量的数量与令牌的数量不匹配”。我成功发布了“searchterm”变量,但无法使查询生效。缺什么?谢谢!

 public function searchAction()
{
    $request = $this->getRequest();

    $searchterm = $request->get('searchterm');

    $em = $this->getDoctrine()->getEntityManager();

    $query = $em->createQuery("SELECT n FROM AcmeNodeBundle:Node n WHERE n.title LIKE '% :searchterm %'")
             ->setParameter('searchterm', $searchterm);

    $entities = $query->getResult();

    return array('entities' => $entities);

}

5 个答案:

答案 0 :(得分:28)

我的Symfony2项目的工作示例:

$qb = $this->createQueryBuilder('u');
$qb->where(
         $qb->expr()->like('u.username', ':user')
     )
     ->setParameter('user','%Andre%')
     ->getQuery()
     ->getResult();

答案 1 :(得分:9)

您应该转储创建的查询以便于调试。

我只能建议您也尝试使用querybuilder:

$qb = $em->createQueryBuilder();
$result = $qb->select('n')->from('Acme\NodeBundle\Entity\Node', 'n')
  ->where( $qb->expr()->like('n.title', $qb->expr()->literal('%' . $searchterm . '%')) )
  ->getQuery()
  ->getResult();

doc

答案 2 :(得分:5)

我认为这个选项也有帮助:

$qb = $this->createQueryBuilder('u');
$qb->where('u.username like :user')
     ->setParameter('user','%hereIsYourName%')
     ->getQuery()
     ->getResult();

答案 3 :(得分:2)

WHERE n.title LIKE'%:searchterm%'

应该是

WHERE n.title LIKE:searchterm

public function searchAction() {
    $request = $this->getRequest();

    $searchterm = $request->get('searchterm');

    $em = $this->getDoctrine()->getEntityManager();

    $query = $em->createQuery("SELECT n FROM AcmeNodeBundle:Node n WHERE n.title LIKE :searchterm")->setParameter('searchterm', $searchterm);

    $entities = $query->getResult();

    return array('entities' => $entities);

}

答案 4 :(得分:0)

也许AcmeNodeBundle\Node?在DQL AcmeNodeBundle:Node :Node - 命名参数