Is there any solution to do this automatically?
My two entities:
class User
{
/* *
* @ManyToMany(targetEntity="Product", inversedBy="users")
* @JoinTable(name="user_product",
* joinColumns={@JoinColumn(name="user_id", referencedColumnName="idUser")},
* inverseJoinColumns={@JoinColumn(name="product_id", referencedColumnName="idProduct")}
*
* )
*/
protected $products;
}
class Product {
/**
* @ManyToMany(targetEntity="User", mappedBy="products")
*/
protected $users;
}
User entity exists with two Products already associated ids (1
, 2
):
$user = $entityManager->find('User', 1);
This array came from view with new Products data to be inserted, deleted or if already in list do nothing:
$array = array(1, 3, 4);
In this case:
1 = Already in association with User (do nothing)
2 = not in array and should be deleted
3 = should be inserted
4 = should be inserted
How to do this in doctrine2? Is there a merge function that do it automatically or shoud I do it manually?
Consider the following code
And
setProducts
defined asIn this case doctrine will delete all the user's product associations and then insert each product association passed in from the view.
I tested this on my system where a
visit
entity is associated to manyvisit_tag
entities. Note that doctrine deletes allvisit_tag
associations for a givenvisit
object in profiler screenshot below and then creates each one.In order to have doctrine only delete/insert associations as needed, you have to manually merge the existing
$user->products ArrayCollection
instead of overwriting it like above. And you can do this efficiently using indexed associations via theindexBy
annotation, which lets you search/add/remove associations by a unique key (i.e. product id) in constant time.Now the profiler shows that doctrine only deletes specific associations (instead of all) and only inserts new associations.
However, in order to do the manual merge doctrine queries the db for all associations, which you would not have to do otherwise. In a nutshell:
Method 1
Method 2
Method 2 is better when the # of associations changed is relatively small compared to the total # of associations. However if you're changing most of your associations, Method 1 seems to be the way to go.