Setting Entity/Document references without hitting the database

In Doctrine 1 when you want to specify a reference you have two options, you can set the foreign key manually:

<?php

$user->setProfileId($profileId);
$user->save();

The problem here is that the profile_id is set in the object but the reference to a Profile instance is not set. The next option is to actually set the object reference:

<?php

$profile = Doctrine_Core::getTable('Profile')->find($profileId);
$user->setProfile($profile);
$user->save();

Here the reference is set properly but the downside to this approach is that it requires us to load the entire Profile object just to set the reference. It is silly! Thanks to the Doctrine2 ORM and MongoDB ODM you have the ability to retrieve a reference to an object without having to hit the database. Here is an example:

<?php

$profile = $em->getReference('Profile', $profileId);
$user->setProfile($profile);
$em->flush();

Or the same thing with the MongoDB ODM:

<?php

$profile = $dm->getReference('Profile', $profileId);
$user->setProfile($profile);
$dm->flush();

Posted in: Doctrine, MongoDB, PHP

Tags: , , ,



1 Comment

rssComments RSS transmitTrackBack Identifier URI


[...] This post was mentioned on Twitter by Jonathan H. Wage and pborreli, Pablo Godel. Pablo Godel said: RT @jwage: New blog post: Setting Entity/Document references without hitting the database http://bit.ly/cSocEX [...]

Pingback by Tweets that mention Jonathan H. Wage » Archive » Setting Entity/Document references without hitting the database -- Topsy.com on July 28, 2010 2:52 pm

addLeave a comment