+ Start a Discussion
ManidManid 

how to create a one to one relationship between two objects using trigger

how to create a one-to-one relation ship between two objects in triggers? 
is it possible? i wonder when a hear this from the interviewer in an interveiw. please post the code if solution is there.
Raj VakatiRaj Vakati
Yes .. .You can stop the records creating  from second child records for parent by using the 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');
        }
    }


 
Other option is , you can able to do it with configuration ( let’s consider the relation between the parent and child is master details , then create rollup summer filed and wrote validation on the rollups summery  field if its count is great than one )

Refer this links 
http://www.infallibletechie.com/2013/05/how-to-create-one-to-one-relationship.html
http://www.forcetree.com/2009/11/one-to-one-relationship-in-salesforce.html

https://medium.com/@MicroPyramid/how-to-create-one-to-one-relationship-between-objects-in-salesforce-b1dfd654de1c

https://salesforce.stackexchange.com/questions/7282/how-to-create-a-one-to-one-relation-between-two-objects