2017-10-17 16 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 { return $ this-> associatedProducts-> contains ($ product); } – STL

+0

그리고 이미 연결된 것과 동일한 두 번째 제품을 추가 할 때이를 덤프하면 false가 반환됩니까? –

답변

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); 
     } 
    }; 
}