有人可能会指出为什么orphanRemoval不适用于以下ManyToMany关系?
我的意思是,中间的many_to_many表获取其行创建/更新/删除但是end / slave表不会删除孤立行 .
非常感谢,继承人是我的映射
Class TaskRecursive
{
/**
* @Assert\Valid
* @ORM\ManyToMany( targetEntity="TaskAttachment", inversedBy="tasks", cascade={ "persist" }, orphanRemoval=true, fetch="EAGER" )
* @ORM\JoinTable(
* name="tasks_attachments",
* joinColumns={@ORM\JoinColumn(name="task_id", referencedColumnName="id", onDelete="CASCADE" )},
* inverseJoinColumns={@ORM\JoinColumn(name="task_attachment_id", referencedColumnName="id")}
* )
*/
private $tasksAttachmentsTask;
Class TaskAttachment
{
/**
* @ORM\ManyToMany( targetEntity="TaskRecursive", mappedBy="tasksAttachmentsTask" )
*/
private $tasks;
注意我没有使用cascade = {“remove”},因为我不希望在移除拥有的侧对象时移除反向对象,我希望当它与拥有的副对象没有更多关系时,移除反向对象 .
解决方法:在我的控制器中,我显式调用 $taskRecursive->setTasksAttachmentsTask( $taskAttachments )
来替换整个集合,因此我编辑了该方法以手动删除孤立集合的对象:
/**
* Set tasksAttachmentsTask
*
* @param \Doctrine\Common\Collections\ArrayCollection $taskAttachmentsTask
* @return TaskRecursive
*/
public function setTasksAttachmentsTask( \Doctrine\Common\Collections\ArrayCollection $taskAttachments )
{
if( $taskAttachments != $this->tasksAttachmentsTask )
{
foreach( $taskAttachments as $tasAttachment )
{
$tasAttachment->addTaskRecursive( $this );
}
$this->_onPropertyChanged( 'tasksAttachmentsTask', $this->tasksAttachmentsTask, $taskAttachments );
//Orphan removal is not working fine, so le'ts removed orphan objects by hand
foreach( $this->tasksAttachmentsTask as $ta )
{
if( !$taskAttachments->contains( $ta ) && $ta->getTasks()->count() < 2 )
{
$this->tasksAttachmentsTask->removeElement( $ta );
}
}
$this->tasksAttachmentsTask = $taskAttachments;
}
return $this;
}