Doctrine2 ManyToMany-relation doesn't save

拟墨画扇 提交于 2019-12-11 11:09:44

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!