2017-03-29 14 views
0

QueryBuilderクエリを実行しようとしていますが、forループの "andWhere"構文が嫌いです。私はそれがforループで何も気に入らないと思う。配列要素のどれかが "x"に等しいかどうかを調べることで、それに基づいて検索結果をフィルタリングします。Symfony 2エラー:配列のメンバー関数andWhere()を呼び出す

$repository = $this->getDoctrine()->getRepository('AppBundle:Shrubs'); 

$query = $repository->createQueryBuilder('p'); 

$shrubs = $query 
    ->where($query->expr()->like('p.botanicalname', ':botanicalname')) 
    ->setParameter('botanicalname', '%' . $botanicalname . '%') 
    ->andwhere($query->expr()->like('p.commonname', ':commonname')) 
    ->setParameter('commonname', '%' . $commonname . '%') 
    ->orderBy('p.commonname', 'ASC') 
    ->getQuery() 
    ->getResult(); 

$checkfor = array("wetsoil"=>"Tolerates Wet Soil", 
    "borderlinehardy"=>"Borderline Hardy", 
    "moistsoil"=>"Prefers Moist Soil"; 

reset($checkfor); 

foreach ($checkfor as $key => $value) { 
    if (${$key} == "x") { 
     $shrubs = $shrubs->andWhere('$key = x') 
      ->setParameter('x', $key) 
      ->getQuery() 
      ->getResult(); 
     return $this->render('shrubs/searchresults.html.twig', array(
      'shrubs' => $shrubs,)); 
    } 
} 

return $this->render('shrubs/searchresults.html.twig', array(
    'shrubs' => $shrubs 
+0

getQuery()を実行しないでください - /前>のgetResultを()で、あなたのforeach。 – Maerlyn

+0

試してみましたが、うまくいきませんでした – bigmammoo

答えて

1

あなた$shrubs変数は、あなたが呼び出す$query結果である->getQuery()->getResult()

あなたのコードは

ようになり、固定

$repository = $this->getDoctrine()->getRepository('AppBundle:Shrubs'); 

$query = $repository->createQueryBuilder('p'); 

$query 
    ->where($query->expr()->like('p.botanicalname', ':botanicalname')) 
    ->setParameter('botanicalname', '%' . $botanicalname . '%') 
    ->andwhere($query->expr()->like('p.commonname', ':commonname')) 
    ->setParameter('commonname', '%' . $commonname . '%') 
    ->orderBy('p.commonname', 'ASC') 
    ; // Remove ->getQuery() and->getResult() 

$checkfor = array("wetsoil"=>"Tolerates Wet Soil", 
    "borderlinehardy"=>"Borderline Hardy", 
    "moistsoil"=>"Prefers Moist Soil"; 

reset($checkfor); 

foreach ($checkfor as $key => $value) { 
    if (${$key} == "x") { 
     $shrubs = $query->andWhere('$key = x') 
      ->setParameter('x', $key) 
      ->getQuery() 
      ->getResult(); 
     return $this->render('shrubs/searchresults.html.twig', array(
      'shrubs' => $shrubs,)); 
    } 
} 

$shrubs = $query->getQuery()->getResult();// Execute the query here 

return $this->render('shrubs/searchresults.html.twig', array(
    'shrubs' => $shrubs 
); 
+0

「[Syntax Error] line 0、col 120:Error:期待されるリテラルは '$'」です。 – bigmammoo

+1

エラーは、 '$ query-> andWhere( '$ key = x')'行では、ここで何を達成しようとしているのか分かりませんが、 '$キー 'は列名であると考えられますので、' $ key-> andWhere( 'p。' key $ = 'x') '(あなたは': 'も忘れてしまいます) – DFayet

+2

And($ {$ key} == "x")も助けにはならない。 foreachループ全体は意味をなさない。低木だけをフィルタリングしたい場合は、array_filterを使用します。 – Cerad

関連する問題