Search code examples
phpsymfonydoctrine-ormdql

Create Doctrine Object by ID without Details from Database Lookup


Each Question object of mine is mapped to a Category object, but I'm attaching the object via AJAX call, so I only know the Category ID when creating the Question, meaning I have do a database read to get the entire Category object.

Can I attach the Category to the Question without having to reach into the database and instantiate the entire Category object? I'm looking to avoid that database lookup...

Working code I'm looking to streamline:

$entityManager = $this->getDoctrine()->getManager();  
$category = $entityManager->getRepository('AcmeBundle:Category')->find($categoryId);

$question = new Question();
...
$question->setCategory($category);
$entityManager->persist($question);
$entityManager->flush();

Solution

  • Get a reference instead. No query needed.

    $category = $entityManager->getReference('AcmeBundle:Category',$categoryId);