如何在数组中搜索?请就以下情况(c)提供建议和特别建议。
我不明白我的错误在哪里。我尝试以多种方式在数组中搜索 Doctrine 列关键字。下面的代码用于调试目的,查询本身在下面的案例中描述。
public function findWhereKeyw($searchArr)
{
print_r('<br> searchstr = '); print_r($searchstr); print_r('</pre>');
print_r('<br> searchstr explode = '); print_r( explode(",",$searchstr) ); print_r('</pre>');
print_r('<br> searchArr implode = '); print_r( implode(",", $searchArr) ); print_r('</pre>');
//searchstr = opera, some
//searchstr explode = Array ( [0] => opera [1] => some )
//searchArr implode = opera,some
$query = ...//see cases below
$qsql=$query->getSQL();
$param=$query->getParameters();
print_r('<br>q= <pre>'); print_r($qsql); print_r('</pre>');
print_r('<br>p= <pre>'); print_r($param); print_r('</pre>');
try {
return $query->getResult();
//return $query->getSingleResult();
} catch (\Doctrine\ORM\NoResultException $e) {
return null;
}
a)以这种方式我得到了错误"Invalid parameter format, ? given, but :<name> or ?<num> expected."
$query = $this->getEntityManager()->createQuery(
'SELECT e.id, e.title FROM MeetingBundle:Event e WHERE e.keywords IN (?)',
explode(",",$searchstr) , array(\Doctrine\DBAL\Connection::PARAM_STR_ARRAY));
或者
$query = $this->getEntityManager()->createQuery(
'SELECT e.id, e.title FROM MeetingBundle:Event e WHERE e.keywords IN (?),
array( array( '.implode(", ",$searchArr).' ) ),
array(\Doctrine\DBAL\Connection::PARAM_STR_ARRAY)'
);
b)以这种方式,我得到空数组:
$qsrtr= 'SELECT e.id, e.title FROM MeetingBundle:Event e WHERE e.keywords IN (';
foreach ($searchArr as $val) {
$qsrtr.= ':'.$val.', ';
}
$qsrtr=rtrim($qsrtr, ", ");
$qsrtr.=')';
print_r('<br> qsrtr= </pre>'); print_r($qsrtr); print_r('</pre>');
$query = $this->getEntityManager()->createQuery( $qsrtr);
foreach ($searchArr as $val) {
$query->setParameter( $val, $val );
//OR $query->setParameter( ':'.$val, $val ); //this line gives also empty array, and the same parameteres object (p) as line above.
} //gives empty array as the result
这打印结果:
qsrtr= SELECT e.id, e.title FROM MeetingBundle:Event e WHERE e.keywords IN (:opera, :some)
q= SELECT e0_.id AS id_0, e0_.title AS title_1 FROM event e0_ WHERE e0_.keywords IN (?, ?)
p= Doctrine\Common\Collections\ArrayCollection Object
(
[elements:Doctrine\Common\Collections\ArrayCollection:private] => Array
(
[0] => Doctrine\ORM\Query\Parameter Object
(
[name:Doctrine\ORM\Query\Parameter:private] => opera
[value:Doctrine\ORM\Query\Parameter:private] => opera
[type:Doctrine\ORM\Query\Parameter:private] => 2
)
[1] => Doctrine\ORM\Query\Parameter Object
(
[name:Doctrine\ORM\Query\Parameter:private] => some
[value:Doctrine\ORM\Query\Parameter:private] => some
[type:Doctrine\ORM\Query\Parameter:private] => 2
)
)
)
从查询 (q) 和参数 (p) 中决定,我应该能够找到带有关键字“opera”的事件。哪里可能出错。关键字字段是由逗号分隔的单词组成的字符串。