我正在尝试使用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();
有一个更好的方法吗?
最佳答案 原则上,你采取的方法很好.但是,我至少看到两件事情是错的.
1)Doctrine不支持BETWEEN,所以你需要这样的东西:
$testquery .= " and p.price >= :minprice AND p.price <= :maxprice";
2).=只是一个字符串运算符,你不能用数组.所以你必须做这样的事情(你可以做一个array_merge,但这似乎有点矫枉过正):
$testParam['minPrice'] = $minPrice;
$testParam['maxPrice'] = $maxPrice;