Doctrine ORM: Updating Associations of an Entity - Fetch all Entities from DB?

16 Views Asked by At

Im new to Doctrine, and using ORM's.

I want to update the join table of an entities association in Doctrine ORM.

I have 2 Entities with a join table for a Many-toMany association

Zoos Table

id zoo_name
1 London Zoo
2 New York Zoo

Animals Table

id animal_name
1 Lion
2 Bear
3 Donkey
4 Otter

Zoos_Animals Join Table

zoo_id animal_id
1 1
1 3
2 1
2 2
2 3
2 4

Historically, when not using an ORM I would post the ID's of all the animals a zoo has, then save in the following way:

1. DELETE FROM zoo_animals WHERE zoo_id = 1
2. FOREACH $_POST['updated_animals'] as $animal_id {
     INSERT INTO zoo_animals ($_POST['zoo_id'], $animal_id
   }

I've simplified this to get my point across, (I would sanitize data etc..)

But when using Doctrine, it seems that even though I have all the information I need in $_POST (an array of animal_id's), in order to update zoo_animals for zoo 1, I need to:

  1. On save run a DQL query which gets all zoo info out along with it's zoo_animals
  2. Build a new ArrayCollection for the Zoo's $animals property by fetching all Animals posted in $_POST['updated_animals']
  3. $zoo->setAnimals($fetchedAnimals) to the ArrayCollection we just fetched
  4. Flush

All I need in my join table is the animal ID's, so it seems really in-efficient that I have to fetch the entire Animal entity for each zoo_animal from the Animals table in order to update the association.

Am I missing something - is there another way to update the join table? - maybe I shouldn't bother recreating the Zoo entity and instead should just deal directly with the join table somehow?

I did also try not fetching the Animals from DB for each $_POST['updated_animals'] and instead just create the Animal with the bare minimum data needed (which I have)

$updatedAnimals = new ArrayCollection();
foreach ($_POST['updated_animals'] as $id){
   $animal = (new Animal())->setId(id);
   $updatedAnimals->add($animal);
}

But when I Flush() I get the following error

A new entity was found through the relationship 'Zoo#animals' that was not configured to cascade persist operations for entity

..basically doctrine doesn't recognise the Animals I created from posted animal ID's, even though they are in the animals table.

As I say, I'm new to using ORM's but all this re-fetching from the DB in order to update seems very inefficient as so I suspect Im doing something wrong.

0

There are 0 best solutions below