2017-10-17 12 views
0

関連製品を追加したり、存在する場合は置き換えようとしています。ここで私が使用しているコードです: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」テーブル内の重複入力エラーをスローしますなぜこの製品が既に関連付けられているかどうかを確認するためのチェックを設定する方法を理解できません。

すべてのヘルプは大、感謝

+0

あなたは 'hasAssociatedProduct'方法には何が私たちを見ることができ、それを考え出したことでしょうか? '$ association-> hasAssociatedProduct($ similar_product)' –

+0

https://github.com/Sylius/Sylius/blob/master/src/Sylius/Component/Product/Model/ProductAssociation.php 公開関数hasAssociatedProduct(ProductInterface $ product ):bool { リターン$ this-> associatedProducts-> contains($ product); } – STL

+0

既に関連付けられている2番目の製品を追加するときにそれをダンプすると、falseを返しますか? –

答えて

1

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); 
     } 
    }; 
} 
関連する問題