【发布时间】:2017-10-17 10:48:20
【问题描述】:
我正在尝试添加关联产品或替换它(如果存在)。这是我正在使用的代码:
/** @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”表中引发重复输入错误,我不知道为什么或如何设置检查此产品是否已关联。
任何帮助将不胜感激,谢谢
【问题讨论】:
-
你能告诉我们
hasAssociatedProduct方法中有什么吗?$association->hasAssociatedProduct($similar_product) -
github.com/Sylius/Sylius/blob/master/src/Sylius/Component/… public function hasAssociatedProduct(ProductInterface $product): bool { return $this->associatedProducts->contains($product); }
-
如果你在添加与已经关联的第二个产品相同的第二个产品时转储它,它会返回 false 吗?
-
是的,它确实返回 false,所以它不能正常工作,但不知道如何检查 $similar_product 是否已经与 $product 关联。 $product->getAssociations() 给出了关联对象的列表,但它只有 -> contains() 方法,该方法采用关联,如果我将 $similar_product 添加到它以进行检查 - 它会引发重复条目错误