May 6, 2013

How to create One to One relationship in Salesforce?

In Salesforce, we have One to Many relationship and Many to Many relationship.

To achieve One to One relationship in Salesforce, kindly follow the below steps

Objects: Interest, Employee.
Relationship: Interest is Master and Employee is Detail.

1. Create a Roll up Summary field on Interest object to find the number of employees(Count).

2. Create a trigger in Employee object to check whether Number Of Employees is equal to one. If it is one, then throw an error, else allow the user to create.


trigger oneToOne on Employee__c (before insert, before update) {
    Set<Id> interestIds = new Set<Id>();
    Map<Id, Interest__c> mapInterest = new Map<Id, Interest__c>();
    for(Employee__c e : trigger.New) {
    List<Interest__c> listInterest = [SELECT Id, Number_of_employees__c FROM Interest__c WHERE Id =: interestIds];
    for(Interest__c intr : listInterest) {
        mapInterest.put(intr.Id, intr);
    for(Employee__c e : trigger.New) {        
        if(mapInterest.get(e.Interest__c).Number_of_employees__c == 1) {
            e.addError('Already an employee has been associated with this interest');



No comments:

Post a Comment