1
votes

I have an entity, "AnnualReport", which accepts a collection of entities, "AnnualReportStaffing". An annual report has four different Staffing sections and hence four of these collections (ArrayCollection). Since I can't use a traditional one-to-many relationship, I have to use One-To-Many with Join Table as described here.

So, for example, one of my Staffing collections is defined as such in my AnnualReport class:

/**
 * @ORM\ManyToMany(targetEntity="AnnualReportStaffing", cascade={"persist"}, orphanRemoval=true, fetch="LAZY")
 * @ORM\JoinTable(name="annualreports_staffingtenure",
 *      joinColumns={@ORM\JoinColumn(name="staffing_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="annualreport_id", referencedColumnName="id")},
 *      )
 */
private $staffing;

Now when it comes time to delete an AnnualReport, Doctrine removes the relationship between the report and the Staffing inside the join table, but it does NOT remove the associated AnnualReportStaffing entities. I tried adding cascade={"remove"}, but I get a foreign key violation because it is trying to remove the Staffing entity before the join table association is deleted.

What is the best way to remove the orphaned Staffing entities? Obviously orphanRemoval=true is not the answer.

2

2 Answers

1
votes

The solution is that you must first detach the Staffing entity from the ORM so it is no longer tracked. After it is detached, it can be removed without the foreign key violation. Also, the inverse column had to have onDelete="CASCADE" set in order to remove the report itself. I'm not positive that this is the safest or most elegant solution, but it seems to work for this particular use case.

/**
 * @ORM\ManyToMany(targetEntity="AnnualReportStaffing", cascade={"persist", "detach", "remove"}, orphanRemoval=true, fetch="LAZY")
 * @ORM\JoinTable(name="annualreports_staffingtenure",
 *      joinColumns={@ORM\JoinColumn(name="annualreport_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="staffing_id", referencedColumnName="id", onDelete="CASCADE")},
 *      )
 */
0
votes

You can try like this:

@ORM\JoinColumn(name="user_id", referencedColumnName="id", onDelete="CASCADE")