Salesforce offers one to many relationship and we can build Many to Many relationship using the concept of Junction object. But what if we want to have One to One relationship.
Well this is quite easy by using configuration only (no code). We have two options by which you can achieve this, lets say we want to achieve one to one relationship between two custom objects – Person__c and Passport__c.
1. Create a lookup field on Passport__c to Person__c.
2. Create a custom field on the Passport__c object. Make the field unique. This field would be used to hold the ID of the associated Person__c.
3. Create a Workflow rule on Passport__c. Update the custom field with the value of the associated Person Id.
Thats it, we have established a one to one relationship between Passport__c and Person__c.
When we try to add a second Passport__c to the Person__c, the “unique” constraint would be violated and an error would be thrown.
This approach will work on both standard and custom object.
1. Create a master detail relationship on Passport__c to Person__c and than on Person__c create a roll up summary field of Passport__c with count.
2. Create a validation rule on Person__c and check if rollup summary field >1.
3. If Person__c has more than one Passport, it will give throw an error.
We can also achieve this by using code to make it more scalable, below are the two ways by which we can implement this-
1. Create lookup fields on both objects, to each other.
2. Write triggers, for any change on these lookups, to either copy the record ID into the other object’s lookup field when the other object’s lookup field is empty, or disallow the change to the original record when the other object’s lookup field is already populated with a different ID from the original record (i.e., already having a one-to-one relation)
Create trigger to check if the child record already exists for a parent, not allowing the user to create the other one unless until first child record id deleted.
Sample example for Person and Passport object-