2

如何在数组中搜索?请就以下情况(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)'
        );

// 根据http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/data-retrieval-and-manipulation.html#list-of-parameters-conversion

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”的事件。哪里可能出错。关键字字段是由逗号分隔的单词组成的字符串。

4

2 回答 2

0

这不是回答如何使用 WHERE .. IN 进行搜索。但它有点用 LIKE 转身,这实际上是比 WHERE -- IN 更好的事件。

简而言之:

        $events = $em->createQuery( 'SELECT e FROM MeetingBundle:Event e WHERE e.'.$colname.' LIKE  :keyw' )
                ->setParameter('keyw', '%'.$val.'%')
                ->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY); 

代码必须重构为 EventRepository 和 EventManager。C:\Bitnami\wampstack-5.5.30-0\sym_prog\proj2_27\src\MeetingBundle\Controller\EventController.php

       /**
         * Search Event entities.  
         *
         * @Route("/search", name="event_search")
         * @Method("GET|POST")
         * @Template("MeetingBundle:Event:ev_search.html.twig")
         */
    public function searchAction(Request $request)
    {
       $post = Request::createFromGlobals();
       $em = $this->getDoctrine()->getManager();

    if ($post->request->has('submit')) {      

        $searchstr=$post->request->get('search_words');       

        $searchArr = $this->multiExplode( [' ',',',';','-'], $searchstr);
        //print_r('searchArr before trim = </pre>'); print_r($searchArr); print_r('</pre>'); 
        foreach ($searchArr as $index => $value) {
             if(strlen(trim($value))==0){
                 unset($searchArr[$index]);
             }
        }
        print_r('searchArr after trim = </pre>'); print_r($searchArr); print_r('</pre>'); 

        $borstatus=$post->request->get('search_or_ck');
        $bor = ($borstatus === 'on' ) ? 1 : 0;
        $bandstatus=$post->request->get('search_and_ck');
        $band = ($bandstatus === 'on' ) ? 1 : 0;

        $bkeyw=$post->request->get('search_keyw'); // check in which table columns to perform search
        $bkeywstatus = ($bkeyw === 'on' ) ? 1 : 0;
        $btitle=$post->request->get('search_title');
        $btitlestatus = ($btitle === 'on' ) ? 1 : 0;
        $bdescr=$post->request->get('search_descr');
        $bdescrstatus = ($bdescr === 'on' ) ? 1 : 0;

        //dump($post);
        print_r('<pre>');  print_r($post);  print_r('</pre>');  
        print_r('********************** bkeyw = ');  print_r($bkeyw);  print_r('<br>');  
        print_r('********************** bkeyw = ');  print_r($bkeywstatus);  print_r('<br>'); 



        $result=array(); //result['colname']=array( 'opera'=> [ '27' => (id='27', title='x',..), '24'=>(),.....]
        foreach ($colnameArr as $colname){
            $keywArr=array(); //keywArr['opera']= [ '27' => (id='27', title='x',..), '24'=>(),.....]
            foreach ($searchArr as $val) { 
                $events = $em->createQuery( 'SELECT e FROM MeetingBundle:Event e WHERE e.'.$colname.' LIKE  :keyw' )
                        ->setParameter('keyw', '%'.$val.'%')
                        ->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
               // $res = $em->getResult(); does not work
               // $res without HYDRATE_ARRAY returns long object, but on this object getId() is not working
               // print_r('<br>*******************result <pre>'); print_r($events); print_r('</pre>');// very long object
                $identArr=array();//$identArr[ '27'] = (id='27', title='x',..)
                foreach ($events as $event){
                    //print_r('<br>*******************result <pre>'); print_r($event'id'); print_r('</pre>');//using ->getResult(\Doctrine\ORM\AbstractQuery::HYDRATE_ARRAY);
                     // print_r('<br>*******************EVENT <pre>'); print_r($event.getId()); print_r('</pre>');// using ->getResult();
                     // print_r('<br>*******************EVENT <pre>'); print_r($event); print_r('</pre>');// very long object //using ->getResult();
                  $id = $event['id'];
                  // all results are unique, because id are unique
                  $identArr[strval($id)]=$event ; //$identArr[ '27'] = (id='27', title='x',..)
                }//foreach ($events as $event)
                $keywArr[$val]=$identArr; //keywArr['opera']= [ '27' => (id='27', title='x',..), '24'=>(),.....]
                unset($identArr);
            }//foreach ($searchArr as $val) {
            $result[$colname] = $keywArr; //result['colname']=array( 'opera'=> [ '27' => (id='27', title='x',..), '24'=>(),.....]
            unset($keywArr);
        } //foreach ($colnameArr as $colname){

// than you have to analyse result, to extract events for cases use selected: OR search, AND search, OR search only in certain columns, AND search only in certain columns... This will give finalArray      

 return array ('res'=>finalArray, )
}
于 2015-12-11T10:27:05.903 回答
0

如果我理解得很好,您正在尝试使用 DQL 进行 IN。这是语法:

// From your Event repository
$qb = $this->createQueryBuilder('e');
$qb->where($qb->expr()->in('r.keywords', explode(",", $searchstr));

我假设您的字段关键字仅包含一个关键字。

于 2015-12-15T01:50:41.250 回答