我具有允许用户创建自定义产品过滤器的逻辑。下面的代码显示了我可以在这些过滤器中稍后在理论中使用它们的部分。它通过默认过滤器(例如价格,类别等)过滤产品,并且用户可以在管理中创建的用户自定义过滤器(例如颜色或宽度)完全独立。如果我仅在默认情况下过滤产品(例如价格或类别),则效果很好。但是,如果我在查询中应用用户的自定义过滤器,则价格过滤器将无法正常工作。它仅按类别,子类别和其他类别过滤产品
这是我解析过滤器以创建模型的代码
function adicionaAoCart(title, price) {
let linhaCart = document.createElement("div")
let itensCart = document.getElementsByClassName("itens-cart")[0]
linhaCart.classList.add("linha-cart")
let itemNomeCart = itensCart.getElementsByClassName("cart-item-title")
for (i = 0; i < itemNomeCart.length; i++) {
if (itemNomeCart[i].innerText == title) {
alert("This item has already been added.")
return
}
}
let conteudoCart = `
<div class="cart-item cart-column">
<span class="cart-item-title">${title}</span>
</div>
<span class="cart-price cart-column">${price}</span>
<input class="cart-quantity-input" type="number" value="1">
<button class="btn btn-danger" type="button">X</button>
</div>
`
linhaCart.innerHTML = conteudoCart;
itensCart.append(linhaCart)
linhaCart.getElementsByClassName("btn-danger")[0].addEventListener("click", removeCartItem)
linhaCart.getElementsByClassName("cart-quantity-input")[0].addEventListener("change", quantityChanged)
cartArray = []
cartArray.push(itensCart)
localStorage.setItem('itens', JSON.stringify(cartArray))
const data = JSON.parse(localStorage.getItem('itens'))
data.forEach(item => {
adicionaAoCart(item)
})
}
if ($option === ProductFilter::TYPE_SUB_CATEGORY) {
$filter = new ProductFilter();
$subCategory = $this->em->getRepository(SubCategory::class)->findOneBy(['id' => $value]);
$filter->setSpecification($subCategory);
$filter->setType(ProductFilter::TYPE_SUB_CATEGORY);
$filter->setValue($value);
array_push($filters, $filter);
}
规范实体是用户的自定义过滤器。关系是: 产品->产品规格->规格 产品-> specificationValue(字符串)
这是一个dql查询,当我应用用户的自定义过滤器和价格过滤器时,我会通过$ qb-> getDql()得到
/**
* If product specification is already in array we add current parsed value to it
*/
/** @var ProductFilter $filter */
foreach ($filters as $filter) {
if (
!is_array($filter->getSpecification()) &&
$filter->getSpecification()->getId() === $filterParser->getSpecification()
) {
if (!empty($filterParser->getValue())) {
$filter->addValue($filterParser->getValue());
}
}
}
这是我仅使用默认过滤器的结果
SELECT p, pc, pd FROM AppBundle\Entity\Product p LEFT JOIN p.category pc LEFT JOIN p.subCategory psc LEFT JOIN p.details pd LEFT JOIN p.specifications ps LEFT JOIN ps.specification s WHERE ((((pd.price >= :min AND pd.price <= :max AND s.id = :id1) OR s.id = :id1) AND ps.specificationValue in (:values) AND s.id = :id2) OR s.id = :id2) AND ps.specificationValue in (:values) AND pc.id = :category AND pc.id = :subCategory ORDER BY p.creationDate DESC"
这是我的ProductRepository代码
SELECT p, pc, pd FROM AppBundle\Entity\Product p LEFT JOIN p.category pc LEFT JOIN p.subCategory psc LEFT JOIN p.details pd LEFT JOIN p.specifications ps LEFT JOIN ps.specification s WHERE pd.price >= :min AND pd.price <= :max AND pc.id = :category AND pc.id = :subCategory ORDER BY p.creationDate DESC