2013-10-24 30 views
0

我需要使用已存在的相同數據創建一組新的DB記錄。見下圖:使用Symfony2和Doctrine2從DB中存在的對象創建新對象

enter image description here

以此爲例子,我需要創建一組相同的記錄,但只是改變了列的公司,少走UPC = I5TYF1UPORMYUY4JT21Z,使用這種信息,我應該能夠僅僅產生兩行將公司更改爲52(任意數量)。我認爲是使用這個來獲取這些記錄:

$entityStockDetailHasProductDetail = $this->getDoctrine()->getManager()->getRepository('ProductBundle:StockDetailHasProductDetail')->findBy(array(
    "product" => $request->request->get('product')['id'], 
    "upc" => $request->request->get('product')['upc'], 
)); 

哪個會返回正確的記錄,但我不知道如何從這一點繼續。我的實體擁有所有這些方法:

$entityStockDetailHasProductDetail->setProductDetail(); 
$entityStockDetailHasProductDetail->setUpc(); 
$entityStockDetailHasProductDetail->setProduct(); 
$entityStockDetailHasProductDetail->setCompany(); 
$entityStockDetailHasProductDetail->setCondition(); 
$entityStockDetailHasProductDetail->setContent(); 

任何想法?

回答

2

Just loop over the collection,clone your entities,set the new company and persist。

$em = $this->getDoctrine()->getEntityManager('default'); 
$collection = $em->getRepository('YourBundle:Entity')->findBy(array('...')); 

foreach ($collection as $entity) { 
    $newEntity = clone $entity; 
    $newEntity 
     ->setId(null) 
     ->setCompany($company) 
    ; 
    $em->persist($newEntity); 
} 
$em->flush(); 
+0

感謝這正是我一直在尋找 – Reynier