我有一个数据源,我使用for循环来处理。数据源有时可能有重复。我循环遍历数据源并创建" item"实体。我试图避免这些重复,但我认为由于项目尚未发送到数据库,因此在重复检查期间找不到它们。
这是我的伪 for循环:
foreach($datasource['data'] as $post){
$dupe = $em->getRepository('AppBundle:Item')->findOneByDatasourceId($post['id']);
if(!$dupe){
//process the item
$item = new Item();
$item->setDatasourceId($post['id']);
$em->persist($item);
}
}
$em->flush();
这确实找到重复。
如果尚未将数据发送到数据库,如何找到重复项?我的印象是实体经理会知道尚未推出的数据。
由于
答案 0 :(得分:1)
EntityManager :: find不检查等待持久化的项目。这些项目存储在一个工作对象单元中,理论上你可以检查它。但这有点痛苦。正如@Matteo建议的那样,你也可以在每次持续之后刷新,但这会影响性能。
很容易让你拥有本地缓存:
$datasourceCache = [];
foreach($datasource['data'] as $post){
$postId = $post['id'];
if (!isset($datasourceCache[$postID] (
$datasourceCache[$postID] = true;
$dupe = $em->getRepository('AppBundle:Item')->findOneByDatasourceId($postId);
if(!$dupe){
//process the item
$item = new Item();
$item->setDatasourceId($postId);
$em->persist($item);
}
}
}
$em->flush();