I play a little with Symfony2 and Doctrine2.
I have an Entity that has a unique title, for example:
class listItem { protected $id; protected $title;
now I get json and update my database with these elements:
$em = $this->get('doctrine.orm.entity_manager'); foreach($json->value->items as $item) { $listItem = new ListItem(); $listItem->setTitle($item->title); $em->persist($listItem); } $em->flush();
works great for the first time. but the second time I get a sql error (of course): Integrity constraint violation: 1062 Duplicate entry
sometimes my json file is updated, and some of them are new, some are not. Is there a way to tell the entity manager to skip duplicate files and just insert new ones?
What is the best way to do this?
Thanks for the help. Please leave a comment if something is unclear
Edit:
what works for me does something like this:
$uniqueness = $em->getRepository('ListItem')->checkUniqueness($item->title); if(false == $uniqueness) { continue; } $listItem = new ListItem(); $listItem->setTitle($item->title); $em->persist($listItem); $em->flush(); }
checkUniqueness is a method in my ListItem registry that checks if the header is already in my db.
This is terrible. These are 2 database queries for each item. it ends with about 85 database queries for this action.
source share