2013-01-07 86 views
0

我想爲我的數據庫建立過濾器。基於幾個表單輸入的值,我需要構建適當的查詢。這是代碼:建立動態學說查詢

$qb = $em->createQueryBuilder(); 
      $qb->select('c.title') 
      ->from('Baza\BlogBundle\Entity\Conferences', 'c');   
    $conditions=array(
     $qb->expr()->gt('c.title',$enquiry->getNaziv()));//First condition 

    if ($enquiry->getKontakt()!=null) { 
     $conditions[] = $qb->expr()->lt('c.contactemail',$enquiry->getKontakt())}//Adding second, optional condition 

    $conditions = call_user_func_array(array($qb, 'andX'), $conditions); 
    $qb->where($conditions); 
    $query = $qb->getQuery(); 

當我運行此我得到如下因素的異常:

Warning: call_user_func_array() expects parameter 1 to be a valid callback, class 'Doctrine\ORM\QueryBuilder' does not have a method 'andX'

*編輯我獲得以下錯誤call_user_func_array()修改後:

QueryException: SELECT c.title FROM Baza\BlogBundle\Entity\Conferences c WHERE c.title > ITRO AND c.contactemail < [email protected]

顯然,查詢格式不正確。我正在關注這篇文章:Doctrine DQL conditional query

有什麼想法?

回答

1

我建用下面的代碼動態查詢:

$em = $this->getDoctrine()->getEntityManager(); 

      $naziv = $enquiry->getNaziv(); 
      $drzava=$enquiry->getDrzava(); 
      $oblast=$enquiry->getOblast(); 
      $grad=$enquiry->getGrad(); 
      $provincija=$enquiry->getProvincija(); 
      $kontakt=$enquiry->getKontakt(); 
      $sajt=$enquiry->getSajt(); 

      $testquery = "SELECT c.title FROM Baza\BlogBundle\Entity\Conferences c JOIN c.topicid t JOIN c.locationid l JOIN l.stateid s WHERE c.lh = :lh"; 
      $testparam ['lh'] = $lh; 

      if ($kontakt != '') { 
        $testquery .= " and c.contactemail = :kontakt"; 
        $testparam['kontakt'] = $kontakt; 
      } 
      if ($drzava != '') { 
        $testquery .= " and s.name = :drzava"; 
        $testparam['drzava'] = $drzava; 
      } 

      if ($provincija != '') { 
        $testquery .= " and l.province = :provincija"; 
        $testparam['provincija'] = $provincija; 
      } 

      if ($grad != '') { 
        $testquery .= " and l.city = :grad"; 
        $testparam['grad'] = $grad; 
      } 

      if ($sajt != '') { 
        $testquery .= " and c.siteurl = :sajt"; 
        $testparam['sajt'] = $sajt; 
      } 

      if ($oblast != '') { 
        $testquery .= " and t.name = :oblast"; 
        $testparam['oblast'] = $oblast; 
      } 

      $query = $em->createQuery($testquery)->setParameters($testparam); 
      $result = $query->getResult(); 
0
  1. 和X是所有小寫
  2. 和X是)EXPR(的函數,而不是查詢生成器:

    $條件= call_user_func_array(陣列($ QB-> EXPR(), '和X' ),$ conditions);

0

關於您的編輯:

$qb = $em->createQueryBuilder(); 
      $qb->select('c') 
      ->from('Baza\BlogBundle\Entity\Conferences', 'c'); 

使用原則(作爲ORM)選擇整個對象。你仍然可以在字段上的where子句。另外GT和LT搜索字符串是不是真的適當的SQL練習。他們可能會因不正確的信件而產生奇怪的結果。

+0

謝謝回覆。嘗試整個對象,我得到同樣的錯誤。如果不是這樣,在Doctrine中處理動態查詢時常見的做法是什麼? – Xardas

+0

在我們真正回答之前,我們需要更好地瞭解您希望用c.contactemail <[email protected](和c.title> ITRO)完成的工作。 – Lighthart

+0

這只是一個簡單的例子,需要進行縮放。對於用戶填寫的每個表單輸入,我需要在條件添加附加條件。如果某些輸入留空,則不需要查詢附件...您明白了。 – Xardas