Sylius,添加/删除/更新相关产品
问题描述:
我试图添加关联产品或将其替换(如果存在)。下面是我使用的代码:Sylius,添加/删除/更新相关产品
/** @var ProductAssociationInterface $association */
$association = $this->associationFactory->createNew();
/** @var ProductAssociationTypeInterface $associationType */
$associationType = $this->associationTypeRepository->findOneBy(['code' => 'similar_products']);
$association->setType($associationType);
if ($similar_product = $this->productRepository->findOneByCode(trim($row['Similar product']), $this->locale)) {
if (!$association->hasAssociatedProduct($similar_product)) {
$association->addAssociatedProduct($similar_product);
}
if (!$product->hasAssociation($association)) {
$product->addAssociation($association);
$this->associationManager->persist($product);
if (!$this->associationRepository->findOneBy(array('owner' => $similar_product->getId(), 'type' => $associationType->getId()))) {
$this->associationRepository->add($association);
}
};
}
,但如果没有相关的产品,而它的工作的伟大 - 如果有,或者即使是相同的产品 - 它抛出一个重复输入错误在“product_association_idx”表我无法确定为什么或如何设置检查以查看此产品是否已关联。
任何帮助将不胜感激,谢谢
答
ok了,想通了自己
/** @var ProductAssociationInterface $association */
$association = $this->associationFactory->createNew();
/** @var ProductAssociationTypeInterface $associationType */
$associationType = $this->associationTypeRepository->findOneBy(['code' => 'similar_products']);
$association->setType($associationType);
if ($similar_product = $this->productRepository->findOneByCode(trim($row['Similar product']), $this->locale)) {
$flag = true;
foreach($product->getAssociations() as $productAssociation) {
if ($productAssociation->hasAssociatedProduct($similar_product)) {
$flag = false;
}
}
if ($flag) {
$association->addAssociatedProduct($similar_product);
$product->addAssociation($association);
$this->associationManager->persist($product);
if (!$this->associationRepository->findOneBy(array('owner' => $similar_product->getId(), 'type' => $associationType->getId()))) {
$this->associationRepository->add($association);
}
};
}
你能告诉我们什么是在'hasAssociatedProduct'方法? '$ association-> hasAssociatedProduct($ similar_product)' –
https://github.com/Sylius/Sylius/blob/master/src/Sylius/Component/Product/Model/ProductAssociation.php public function hasAssociatedProduct(ProductInterface $ product ):bool { return $ this-> associatedProducts-> contains($ product); } – STL
如果您在添加与已关联的第二个产品相同的第二个产品时转储了它,它会返回false吗? –