Setting Entity/Document references without hitting the database post

Posted on 2010-07-28 by jwage


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

$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:

$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:

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

Or the same thing with the MongoDB ODM:

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