Doctrine2:使用ArrayCollection更新一对多关联不会删除项目

时间:2015-03-25 21:06:27

标签: doctrine-orm

使用Doctrine2,Note实体与File实体具有一对多关联。因此,一个笔记可以有许多文件与。

相关联

然后,请考虑以下代码:

/*
 * @entityManager : this is a pre-obtained EntityManager object
 * @notes : expects a Note entity
 * @filesId : expects an array of integer representing file ids
 */
function setNoteFiles($entityManager, $note, $filesId) {
    $files = new ArrayCollection();
    foreach ($filesId as $fileId) {
        $file = $entityManager->find('File', $fileId);
        $file->setNote($note);
        $files->add($file);
    }
    $note->setFiles($files);
    $entityManager->flush();
}

因此,当我想将文件添加到笔记中时,例如使用以下内容,它可以按预期完美地运行:

setNoteFiles($entityManager, $note, Array(1, 2, 3, 4));

但是,如果以后我想删除集合中的一个文件,(当然不使用removeElement!我想设置ArrayCollection本身),如下所示:

setNoteFiles($entityManager, $note, Array(1, 2, 4));

然后,这不起作用。在数据库中,外键列不会对此文件记录进行更新(为空或零)。

Isn教授应该管理新的ArrayCollection以添加项目并删除不再需要的项目吗?

0 个答案:

没有答案