使用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以添加项目并删除不再需要的项目吗?