Search code examples
symfonydoctrinesymfony-2.3

Create new object from existent object in DB using Symfony2 and Doctrine2


I need to create a new set of DB records by using same data that already exists. See image below:

enter image description here

Using this as example I need to create the same set of records but just changing the column company, less take UPC = I5TYF1UPORMYUY4JT21Z, using this info I should be able to generate two rows by just changing the company to 52 (any number). What I think is to get those records using this:

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

Which returns the right records but I don't know how to continue from that point. My entity has all this methods:

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

Any ideas?


Solution

  • 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();