问题
I have a problem with my ManyToMany relation in doctrine2. The relation doesn't persist even though the relation exists. If i check afther the persist in two foreach loops the correct objects are returned.
The first class is Document.
class Document extends BaseEntity
{
....
/**
* @ORM\ManyToMany(targetEntity="Job", mappedBy="documents", cascade={"all"})
* @ORM\JoinTable(name="job_document")
*/
protected $jobs;
....
The second class is Job
class Job extends BaseEntity
{
....
/**
* @ORM\ManyToMany(targetEntity="Document", inversedBy="jobs", cascade={"all"})
* @ORM\JoinTable(name="job_document")
*/
protected $documents;
....
In my controller I do the following:
$job->addDocument($document);
$document->addJob($job);
$em->persist($job);
$em->flush();
The add functions work fine. I can see it when I loop through the objects afther I do this.
回答1:
It seems to me that you only try to update the inverse side and not the owning side of the relationship.
As pointed out in the doctrine documentation:
Changes made only to the inverse side of an association are ignored. Make sure to update both sides of a bidirectional association (or at least the owning side, from Doctrine’s point of view)
来源:https://stackoverflow.com/questions/12779669/doctrine2-manytomany-relation-doesnt-save