Reciprocal or Mirror Records Overview
In this blogpost I will be discussing creating reciprocal relationship records in Force.com using Apex Triggers. I'd first like to say that this use case is one that should be scrutinized before you implement it. Creating reciprocal or mirror relationships of records in Force.com can sometimes create duplicate records. To keep your managed data down, you would often like to avoid this process if possible. However there are times when you just have to keep record values in sync, so carefully evaluate your use case before implementing this. Now that I have the disclaimer out the way here we go!
When working with records in Force.com we sometimes have a need to create a reciprocal relationship between two records. For example, sometimes we may have a use case which involves keeping two records in sync. When you update Record A, you may need to update some corresponding fields on Record B. Below is a simple diagram illustrating this.
Force.com Data Model
The best way to implement this is to have a lookup field on the object which is a lookup to it self. In this case I have create a lookup field on contact called "Linked Contact" and related it to the Contact record as shown in the schema builder diagram below.
Apex Trigger FlowNow that I have the data model configured for the reciprocal relationships, I need to keep the records in sync automatically. This means that whenever Contact record A is updated, make sure to update Contact record B. We can accomplish this via Apex Triggers when a record is inserted or updated to keep the lookup fields in sync, thereby allowing us to "link" the records. However, there is problem with this scenario.
In an Apex Trigger you only have acces to the records Id in the After context, which makes sense. There cannot be an Id until after the record has been created. So the flow would look like this: