Symfony2,doctrine2,createQuery,如何搜索IN数组?

时间:2015-12-10 23:19:00

标签: symfony doctrine-orm where-in createquery

如何在数组中搜索?关于下面的案例(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)); 

OR

$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”的事件。哪里可能是个错误。关键字字段是以逗号分隔的字符串。

2 个答案:

答案 0 :(得分: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 \控制器\ 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, )
}

答案 1 :(得分:0)

如果我理解得很好,你就是想用DQL做一个IN。这是语法:

[mysqld]
datadir=/var/lib/mysql
socket=/var/lib/mysql/mysql.sock
# Disabling symbolic-links is recommended to prevent assorted security risks
symbolic-links=0
# Settings user and group are ignored when systemd is used.
# If you need to run mysqld under a different user or group,
# customize your systemd unit file for mysqld according to the
# instructions in http://fedoraproject.org/wiki/Systemd

[mysqld_safe]
log-error=/var/log/mysqld.log
pid-file=/var/run/mysqld/mysqld.pid

我认为您的字段关键字只包含一个关键字。