Reputation: 10084
I have two entities E1 & E2 with ManyToMany relation and linking table for it. Everything is fine until I'm trying add to E1 element of E2 that doesn't exist. For example, E2 is Tag entity. And user puts a couple of tags via form. How to add non-existent tags in E2 before persisting them to E1?
UPDATE:
Okay, I've updated my entity according to @Axxiss answer. It does persist new tags automaticly but it also persists old tags again. All I whant is if I have a tag with name 'tag1' it shouldn't be added in tags table again.
Upvotes: 0
Views: 156
Reputation: 4789
You need to add cascade
annotation to tag field inside E1.
Inside E1 you will have something like this:
/**
* @ORM\ManyToMany(targetEntity="Tag", cascade={"persist"})
* @ORM\JoinTable(name="e1_has_tags",
* joinColumns={@ORM\JoinColumn(name="e1_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="tag_id", referencedColumnName="id")}
* )
**/
private $tags;
Check Transitive persistence / Cascade Operations
If you want to add a tag only one time you have two options:
On both cases you need to query by the tag name, if the tag already exist replace it with the Tag found.
Upvotes: 1
Reputation: 159
If you want unique Tags you need to check if they exists before persist them.
Upvotes: 1