Suppose you are attempting to create an university Course entity, with a related university Department entity:
$em = $this->get('doctrine')->getEntityManager(); $course= new Course(); $course->setStartDate(20130101); $course->setEndDate(20130401); $dept= $this->get('university.department.service')->findOneById(SOME_DEPT_ID); $course->setDepartment($dept); $em->persist($course); $em->flush();
The Problem That Can AriseDoctrine is 'smart' and knows about Relationships. If configured to cascade the department data, it should save (INSERT or UPDATE) the department along with the course.
However, in the code example above, Doctrine will sometimes attempts to insert the related department, rather than update the department. This is a problem, and you will encounter an error message like this one:
ErrorException: Notice: Undefined index: 000000005118577900000000245708ca in /home/project/vendor/doctrine/lib/Doctrine/ORM/UnitOfWork.php line 2152
This error message is complaining because it's attempting to insert a new Department, when it should be updating the Group. More specifically, the (inserted) Department is colliding with an existing department in the database.
The Solution: EntityManager's getReference()
$em = $this->get('doctrine')->getEntityManager(); $course= new Course(); $course->setStartDate(20000101); $course->setEndDate(20010101); $course->setDepartment($em->getReference('Namespace\Of\Department,LoadDepartmentData::SOME_DEPT_ID));
In the above example, there isn't an explicit DB fetch, and Doctrine is smart enough to avoid the MySQL read in this case. As a result, the second version is more efficient.
More Reading on thisIt's important to read up and understand what Doctrine is doing here, and know how to best use Doctrine Reference Entities.