I've been trying to figure out how to get this to work for along time but without any luck. Due to a complex logic in an app I'm working on, I need to create an isolated clone
of a entity collection without preserving what so ever relation to the database. Whatever changes I do on the cloned collection should not be tracked by Doctrine at all and should be treated as if it doesn't exist at all.
Here's an example code:
/*
* @ORM\Entity()
*/
class Person
{
/**
* @var integer
*
* @ORM\Id
* @ORM\Column(name="person_id", type="integer",nullable=false)
* @ORM\GeneratedValue(strategy="AUTO")
*/
public $id;
/**
* @var ArrayCollection
*
* @ORM\OneToMany(targetEntity="Car", mappedBy="person", cascade={"persist"})
*/
public $cars;
}
/**
* @ORM\Entity()
* @ORM\HasLifecycleCallbacks()
*/
class Car
{
/**
* @var integer
*
* @ORM\Id
* @ORM\Column(name="car_id", type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/*
* @ORM\JoinColumn(name="person_id", referencedColumnName="person_id", nullable=true)
* @ORM\ManyToOne(targetEntity="Person", inversedBy="cars", cascade={"persist"})
*/
private $person;
}
I've already tried the following code in my controller to store the collection into the session but it still somehow stores the relationships:
$tmp = clone $person;
$this->get('session')->set('carCollection', $tmp->getCars());
$tmpCars = clone $person->getCars();
$tmpCollection = new ArrayCollection();
foreach($tmpCars as $car) {
$tmpCollection->add(clone $car);
}
$this->get('session')->set('carCollection', $tmpCollection);
$tmpCars = clone $person->getCars();
$tmpCollection = new ArrayCollection();
foreach($tmpCars as $car) {
$clone = clone $car;
$entityManager->detach($car);
$tmpCollection->add(clone $clone);
}
$this->get('session')->set('carCollection', $tmpCollection);
Apparently I'm doing something wrong here because I end up having more results in the Car
collection when flush
ing the entity even though the collection itself has the correct number of records. I have a suspicion that somewhere in the chain Doctrine doesn't compute correctly what needs to be done.
Any ideas or directions on how to solve or debug this?
Follow-up question: When retrieving back the cloned collection from the session will it still be an isolated clone or Doctrine will try merge it back?