Symfony 2 Error: Call to a member function andWhere() on array

Symfony 2 Error: Call to a member function andWhere() on array

我正在尝试执行 QueryBuilder 查询,但它不喜欢 for 循环中的 "andWhere" 语法。我认为它不喜欢 for 循环中的任何内容。它应该检查是否有任何数组元素等于 "x",以便它根据该元素过滤搜索结果。

$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

你的$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
);