在doctrine2中忽略flush上的某些实体

时间:2018-04-08 22:50:35

标签: php symfony doctrine-orm orm entity

我有以下循环[编辑]不起作用[/编辑]。

背景:我正在symfony4 / doctrine2项目中导入一组记录。我想避免重复的条目。当我解析记录时,如果检测到重复,则会被忽略,但如果它真的是唯一的,那么它将被持久化以供flush()命令稍后执行。

我发现当我找到重复的记录时,我不能简单地忽略它;相反,我必须发出$em->clear()命令。否则我会违反完整性(我对我的实体有一个限制,强制将“'代码”字段设置为在我的实体上唯一)。

ServiceCode实体:

class ServiceCode
{
    // omitting id and other properties

    /**
     * @ORM\Column(type="string", unique=true)
     */
    private $code;

    // omitting getters and setters
}

循环导入新的ServiceCodes:

foreach($records as $record) {
    $code = $record['code'];

    $newServiceCode = new ServiceCode();
    $newServiceCode->setCode($code);

    /** Avoid duplicate records **/
    $existingServiceCode = $em->getRepository(ServiceCode::class)
        ->findOneBy(['code' => $newServiceCode->getCode()]);

    if ($existingServiceCode) {
        $em->clear(); // this clears everything, so it's the wrong solution
        ++$duplicateCount;
    } else {
        // persist and save the new code
        $em->persist($newServiceCode);
        ++$importedCount;
    }
}
$em->flush();

我修改过的问题:如何解析记录并忽略重复项,然后只导入新的/唯一的记录?

我已经看到了一些相关的问题,但是这些问题与从数据库中提取的实体有关,因为实体是从数据库中产生的,所以不需要持久化。情况并非如此。

0 个答案:

没有答案
相关问题