Crafting Seamless One-to-One Relationships in Salesforce
Gaurav Gupta
Salesforce Technical Architect | 15X Certified | Trainer | Double Ranger | Blogger
Creating a one-to-one relationship between custom objects in Salesforce might seem like a puzzle, especially when Salesforce doesn't offer a direct method.
In this blog, we'll explore user-friendly ways to establish a seamless connection between two objects, say, 'Employee' and 'Aadhar Card.'
Option 1: The Configuration Route
This configuration ensures that trying to add a second Aadhar Card to an Employee triggers an error due to the unique constraint.
Option 2: Master-Detail Mastery
This setup ensures a straightforward one-to-one connection; an error will pop up if an Employee attempts to have more than one Aadhar Card.
领英推荐
Option 3: The Mutual Lookup Approach
This approach maintains a clear one-to-one relationship by managing associations between 'Aadhar Card' and 'Employee.'
Option 4: Trigger Checkup
Here's a simplified example showcasing the connection between 'Employee' and 'Aadhar Card' using triggers.
trigger AadharCardValidation on Aadhar_Card__c (before insert) {
Set<Id> empIdSet = new Set<Id>();
for (Aadhar_Card__c aadhar : Trigger.New) {
empIdSet.add(aadhar.Employee__c);
}
for (Employee__c emp : [SELECT Id, (SELECT Id FROM Aadhar_Cards__r) FROM Employee__c WHERE Id IN :empIdSet]) {
for (Aadhar_Card__c aadhar : Trigger.New) {
if (emp.Aadhar_Cards__r.size() > 0) {
aadhar.addError('An Aadhar Card already exists for the Employee: ' + emp.Name);
}
}
}
}
With these user-friendly options, building one-to-one relationships in Salesforce becomes a breeze. Each approach caters to different needs, providing flexibility and control over your data connections.