Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you get a foreign key from an object in Doctrine2 without loading that object?

Tags:

I'm working on an events site and have a one to many relationship between a production and its performances, when I have a performance object if I need its production id at the moment I have to do

$productionId = $performance->getProduction()->getId();

In cases when I literally just need the production id it seems like a waste to send off another database query to get a value that's already in the object somewhere. Is there a way round this?

like image 912
pogo Avatar asked Nov 21 '11 12:11

pogo


1 Answers

Edit 2013.02.17:
What I wrote below is no longer true. You don't have to do anything in the scenario outlined in the question, because Doctrine is clever enough to load the id fields into related entities, so the proxy objects will already contain the id, and it will not issue another call to the database.

Outdated answer below:

It is possible, but it is unadvised.

The reason behind that, is Doctrine tries to truly adhere to the principle that your entities should form an object graph, where the foreign keys have no place, because they are just "artifacts", that come from the way relational databases work.

You should rewrite the association to be

  • eager loaded, if you always need the related entity
  • write a DQL query (preferably on a Repository) to fetch-join the related entity
  • let it lazy-load the related entity by calling a getter on it

If you are not convinced, and really want to avoid all of the above, there are two ways (that I know of), to get the id of a related object, without triggering a load, and without resorting to tricks like reflection and serialization:

If you already have the object in hand, you can retrieve the inner UnitOfWork object that Doctrine uses internally, and use it's getEntityIdentifier() method, passing it the unloaded entity (the proxy object). It will return you the id, without triggering the lazy-load.

Assuming you have many-to-one relation, with multiple articles belonging to a category:

$articleId = 1;
$article = $em->find('Article', $articleId);
$categoryId = $em->getUnitOfWork()->getEntityIdentifier($article->getCategory());

Coming 2.2, you will be able to use the IDENTITY DQL function, to select just a foreign key, like this:

SELECT IDENTITY(u.Group) AS group_id FROM User u WHERE u.id = ?0

It is already committed to the development versions.

Still, you should really try to stick to one of the "correct" methods.

like image 146
K. Norbert Avatar answered Sep 28 '22 00:09

K. Norbert