我正在建立二手车的搜索表单。在表单中,用户可以选择汽车应具有的选项的复选框。因为用户可以选择多个选项,所以我需要搜索具有用户选择的所有选项的汽车。
我正在尝试构建一个查询“汽车”的查询。有选择的选项。现在我可以通过执行以下操作来检查汽车是否具有所选选项之一:
// The options filter is something special, the parameter is passed as a comma separated
// String with options ids
if($param == 'car.options' && $optionsIds){
$queryBuilder->leftJoin('car.options', 'option');
$options = $queryBuilder->expr()->orX();
foreach(explode(',', $optionsIds) as $id) {
$options->add($queryBuilder->expr()->eq('option.id', $id));
}
$wheres->add($options);
continue;
}
但是,当我改变' orX'用'和X'结果总是返回空。
上面的代码片段是更大功能的一部分。
答案 0 :(得分:0)
我终于成功了。诀窍是使用子查询:
$carsWithSelectedOptions = $this->getEntityManager()->createQuery('
SELECT c.id
FROM Occasions\Model\Bo\Car AS c JOIN c.options o
WHERE o.id IN ('.$optionsIds.')
AND c.id = car.id
GROUP BY c.id
HAVING COUNT(o.id) >= '.count(explode(',', $optionsIds))
);
$wheres->add($queryBuilder->expr()->exists($carsWithSelectedOptions->getDQL()));
请注意,这是较大查询的一部分。完整查询结果为:
SELECT advert, customer, car, country, brand, model
FROM Occasions\Model\Bo\Advert advert
LEFT JOIN advert.customer customer
LEFT JOIN advert.car car
LEFT JOIN customer.country country
LEFT JOIN car.model model
LEFT JOIN car.brand brand
WHERE EXISTS(
SELECT c.id FROM Occasions\Model\Bo\Car AS c
JOIN c.options o WHERE o.id IN (2,4,5,51)
AND c.id = car.id GROUP BY c.id HAVING COUNT(o.id) >= 4)
AND brand.id = :brandid
AND model.id = :modelid
AND country.country_code = :countrycountry_code