Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony - Memory problem on flush for ManytoMany relations

On my symfony project (5.x version), I have a simple ManyToMany relation between Metas and Tags (no fetch and no cascade defined).

class Meta
{
    ...

    /**
     * @ORM\ManyToMany(targetEntity="Tag", mappedBy="meta")
     * @ORM\OrderBy({"name" = "ASC"})
     */
    protected $tags;
}
class Tag
{
    ...

    /**
     * @ORM\ManyToMany(targetEntity="Meta", inversedBy="tags")
     * @ORM\JoinTable(name="app_meta_tag")
     * @ORM\JoinColumn(name="meta_id")
     */
    protected $meta;
}

I can have 40 000 metas having the same tag (for example "test").

When I add the "test" tag to a Meta, then persist and flush, all the Metas related to this tag are flushed ... and return a 500 error because of memory limit. This behaviour seems to be in contradiction with doctrine doc : https://www.doctrine-project.org/projects/doctrine-orm/en/2.7/reference/working-with-associations.html#persistence-by-reachability-cascade-persist

Can someone have an explanation about this ? Thanks !

like image 742
ArGh Avatar asked Sep 18 '25 02:09

ArGh


2 Answers

When you associate two entities in Doctrine you have an owning and an inverse side, on update of the owning side Doctrine will save all the inversed side linked. In the opposite case nothings will be saved.

Here the owning side is Tag (inversed-by="tags") which means update will only occur if you update the Tag.

You should reverse mappedBy and inversedBy target class.

like image 135
Mohameth Avatar answered Sep 19 '25 19:09

Mohameth


As we have an elasticsearch database allowing us to get all metas for a tag, I finally I found a woking solution : making the relation unidirectional.

https://www.doctrine-project.org/projects/doctrine-orm/en/latest/reference/association-mapping.html#many-to-many-unidirectional

like image 27
ArGh Avatar answered Sep 19 '25 17:09

ArGh