Doctrine 2动态查询

时间:2012-11-22 17:56:23

标签: php mysql symfony doctrine

我正在尝试使用doctrine进行动态搜索查询。它不起作用

$em = $this->getDoctrine()->getEntityManager();
$city = 'new york';
$minprice = 500;
$maxprice = 1000;

$testquery = "SELECT p FROM AcmeTestBundle:Car p WHERE p.city = :city";
$testparam = array('city' => $city,);

if ($minprice != '') {
    if ($maxprice != '') {
        $testquery .= " and p.price BETWEEN :minprice AND :maxprice";
        $testparam .= array(
            'minprice' => $minprice,
            'maxprice' => $maxprice,
            );
    }
}

$testquery .= " ORDER BY p.price ASC";

$query = $em->createQuery($testquery)->setParameters($testparam);

$result = $query->getResult();

有更好的方法吗?

2 个答案:

答案 0 :(得分:2)

原则上,你采取的方法很好。但是,我至少可以看到两件事情。

1)Doctrine不支持BETWEEN,所以你需要这样的东西:

    $testquery .= " and p.price >= :minprice AND p.price <= :maxprice";

2)。=只是一个字符串运算符,你不能用数组。所以你必须做这样的事情(你可以做一个array_merge,但这看起来有点矫枉过正):

    $testParam['minPrice'] = $minPrice;
    $testParam['maxPrice'] = $maxPrice;

答案 1 :(得分:0)

在php中,您不能将.=与数组一起使用。相反,做

$testparam['minprice'] = $minprice;
$testparam['maxprice'] = $maxprice;