12 Mar 2016

One-To-One Relationship

1.One-To-One (or) Hierarchy 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:

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) {
        interestIds.add(e.Interest__c);
    }
    
    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');
        }
    }
}

Output: