+ Start a Discussion

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) {
    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