1

我有一组术语,我想在一个 Doctrine 2 查询中使用 LIKE 通配符进行匹配。数据库是 SQL,我使用的是 DQL,但查询构建器解决方案会很好。我当前的查询设置是这样的:

foreach($textterms as $text)
{
$parameters[] = '%-'.$text.'-%';
}

$em = $this->getDoctrine()->getManager();
$query = $em->createQuery(
'SELECT p FROM Post p WHERE p.searchfield IN LIKE (:text) ORDER BY p.datetime DESC'
        )->setParameter('text', $parameters);
        $posts = $query->getResult();

但是我得到了 symfony 错误“QueryException: [Syntax Error] line 0, col 62: Error: Expected Literal, got '('”

这个查询在教义中可能吗?

4

1 回答 1

1

您收到此类错误是因为查询在 LIKE 语句之后需要一个值。没有像“IN LIKE”这样的东西。我会考虑的可能解决方案:

// Query Builder added to show difference in code readability I personally use queryBuilder mostly
$query = $this->getDoctrine()->getManager()->createQueryBuilder();
$query->select('p')
        ->from('Post', 'p')
        ->orderBy('p.datetime', 'DESC');
$i = 0;
$parameters = array();
foreach ($textterms as $key => $text)
{
    $query->orWhere('p.searchfield LIKE ?' . $i++);
    $parameters[] = '%-' . $text . '-%';
}
$query->setParameters($parameters);
$posts = $query->getQuery()->getResult();

// Query
$orX = new \Doctrine\ORM\Query\Expr\Orx();
$i = 0;
$parameters = array();
foreach ($textterms as $text)
{
    $orX->add('p.searchfield LIKE ?' . $i++);
    $parameters[] = '%-' . $text . '-%';
}
$orX = (string)$orX;
if(!empty($orX))
{
    $orX = 'WHERE ' . $orX;
}
$sql = sprintf('SELECT p FROM Post p %s ORDER BY p.datetime DESC', $orX);
$query = $this->getDoctrine()->getManager()->createQuery($sql);
$query->setParameters($parameters);
$posts = $query->getResult();
于 2012-10-25T19:32:51.583 回答