2017-03-08 96 views
0

我需要根據字符串從數據庫中提取5個不同的Date類型值。當我的phpmyadmin運行SQL查詢的結果是正確的:從docdb中的數據庫獲取類似於字符串的提取日期

SELECT DISTINCT `date` FROM `collection` WHERE `date` LIKE "%2015-%" ORDER BY `collection`.`date` DESC LIMIT 0,5 

結果:

  • 2015年12月31日
  • 2015年12月30日
  • 2015年12月29日
  • 2015-11-30
  • 2015-11-28

但是當我用Doctrine構建查詢時,它基本上會返回最新的5個日期。它看起來像「LIKE」語句被忽略。這裏是POST控制器:

/** 
* @Route("/collection/InputHint", name="collectionInputHint") 
* @Method("POST") 
*/ 
public function collectionInputHint(Request $request) 
{ 
    $string = $request->get('value'); 
    $entity = $request->get('entity'); 
    $entityColumn = $request->get('entity-column'); 
    $entityType = $request->get('entity-type'); 
    $result = array(); 

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

    $objects = $em 
    ->getRepository('AppBundle:'.$entity) 
    ->createQueryBuilder($entity) 
    ->select($entity.'.'.$entityColumn) 
    ->distinct($entity.'.'.$entityColumn) 
    ->where($entity.'.'.$entityColumn.' LIKE :string') 
    ->setParameter('string', '%'.$string.'%') 
    ->orderBy($entity.'.'.$entityColumn, 'DESC') 
    ->setMaxResults(5) 
    ->getQuery() 
    ->getResult(); 

    foreach ($objects as $object) { 
     $value = ($entityType == 'date') ? $object[$entityColumn]->format("Y-m-d") : $object[$entityColumn]; 
     array_push($result, (string)$value); 
    } 

    return new Response(json_encode($result)); 
} 

和教義的結果是:

  • 2016年1月30日
  • 2016年1月29日
  • 2015年12月31日
  • 2015年-12-30
  • 2015-12-28

請注意,前2個結果與其他結果的相似性不如$ string。另外,如果我將訂單更改爲ASC,則從2013年起有5個日期,因此訂單在這裏不成問題。有任何想法嗎?

+0

您是否已經使用了調試環境:將'app_dev.php'附加到URL,然後單擊底部的'queries'鏈接,然後查看數據庫查詢以查看實際運行的內容? –

+0

@AlvinBunk是的,教條查詢日誌顯示:SELECT DISTINCT f0_.date AS date_0 FROM collection f0_ WHERE f0_.date LIKE? ORDER BY f0_.date DESC LIMIT 5 OFFSET 0 – qerigan

回答

0

我覺得這一條線的問題,它應該是很明顯,當我第一次看:

->setParameter('string', '"%'.$string.'%"') 

改變這種狀況,和我相當肯定它會工作!

+0

難道你認爲我應該得到至少1個upvote嗎?很明顯,我幫你找到了問題! –

0

好的,我發現了這個問題。原來,$ string實際上是空的,所以查詢看起來像:... WHERE'date'LIKE'%%'...

在JS中,我試圖從錯誤/不存在的對象。

經過JS修復後,結果最終正確,因此控制器代碼工作正常。