Skip to main content
Hi,

I have four objects and want to create relationships between them.

      Course

        Batch

        Student

        Trainer

    Estalbish the relationships based on the below requirements

        - One student can be part of multiple courses.

        - One student can be part of multiple batches.

        - One Course can be related to multiple batches

        - One Batch can be associated to only one course at a time.

        - One Trainer can be part of multiple batches and multiple courses

Thanks

Mike
2 answers
  1. Jul 31, 2024, 10:21 AM

    Suppose there are 2 objects - Employee (parent) and Pan Card (child) and we need to make a One-To-One relationship between them. Then we can use any one of the following approaches. 

     

    Approach 1: (unique field + flow)

     

    - Create a lookup field on PAN_Card__c to Employee__c.

    - Create a custom field on the PAN_Card__c object and make the field unique. This field would be used to hold the ID of the associated Employee__c. Hide this field from all page layouts.

    - Create a Flow/Workflow rule on PAN_Card__c. For any change of the lookup field on PAN_Card__c object, update the custom field on the PAN_Card__c object with the value of the associated Employee Id.

    - We have now established a one to one relationship between PAN_Card__c and Employee__c. When we try to add a second PAN_Card__c to the Employee__c, the “unique” constraint would be violated and an error would be thrown. 

     

    Approach 2 : (rollup + validation)

     

    - Create a master detail relationship on PAN_Card__c to Employee__c object.

    - Create a roll up summary field on Employee__c object of PAN_Card__c with count type.

    - Create a validation rule on Employee__c object rollup summary field to check if count > 1.

    - In this way also, We have established a one to one relationship between PAN_Card__c and Employee__c. So it will throw an error if Employee__c has more than one PAN Card.

     

    Approach 3 : (trigger)

     

    - Create a trigger on PAN_Card__c object to check if the PAN Card record already exists for an Employee. If it exist, then throw an error, else allow the user to create.

     

    trigger PANCardValidation on PAN_Card__c (before insert, before update) {

    Set<id> employeeIds = new Set<id>();

    Map<id, Employee__c> mapEmployee = new Map<id, Employee__c>();

    for (PAN_Card__c p : trigger.New) {

    employeeIds.add(p.Employee__c);

    }

    List<Employee__c> lstEmployee = [SELECT Id, Name FROM Employee__c WHERE Id IN : employeeIds];

    if (!lstEmployee.isEmpty()) {

    for (Employee__c emp : lstEmployee) {

    mapEmployee.put(emp.Id, emp);

    }

    for (PAN_Card__c p : trigger.New) {

    if (mapEmployee.containsKey(p.Employee__c)) {

    p.addError('A PAN Card already exist for the employee - ' + mapEmployee.get(p.Employee__c).Name);

    }

    }

    }

    }

0/9000