Sylius,添加/删除/更新相关产品

时间:2017-10-17 10:48:21

标签: symfony 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"中产生重复的输入错误。表格,我无法确定为何或如何设置检查以查看此产品是否已关联。

非常感谢任何帮助,谢谢

1 个答案:

答案 0 :(得分:1)

好吧,自己想通了

/** @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);
        }
    };
}