我有一系列我想在一个学说2查询中使用类似通配符匹配的术语。数据库是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();
,但我得到了符号错误 " queryException:[语法错误]第0行,col 62:错误:预期字面,获得'('"
这个查询在学说中是否可能?
您正在收到此类错误,因为查询期望在类似语句之后会带来值。没有这样的东西"像"。我要考虑的可能解决方案:
// 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 DoctrineORMQueryExprOrx();
$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();