Monday, October 14, 2013

Inserting records in Apex with Many to Many Relationship

The below post helps to insert records with junction objects using apex to establish a many to many relation ship.
I browse through different forums but i could not find the concrete ans .Below is the one easy way you can insert as many records as you want in junction object.

Scenario: A student can attend multiple classes and one class can have multiple students..

 While saving the class record i need to add the selected student records as well.

1.Class is one object(api name: Class__c). (fields : Standard field Name)
2.Student is second object (api name: Student__c).(fields : Name, attendence)
3.Course is junction object(api name : Course__c) (fields: .toClass__c(Master detail to Class), .toStudent__c(Master detail to Student). 


 Class__c c1=new Class__c(Name='Maths');
       insert c1;
       List<course__C> cc1=new List<Course__c>();
       integer i=0;
// you can fetch the selected records..
      List<Student__c> stuList=[select ID from Student__c where ID= 'a0Ei0000005GOIK' or  id='a0Ei0000005GOFC'];
     
       for(Student__c ss:stulist){
           course__C cc=new Course__c();
           cc.Name='Bachelors Degree'+(i+1);
           if(cc.toClass__c!=c1.Id){     
               cc.toClass__c=c1.Id;}
           cc.toStudent__c=ss.ID;
           cc1.add(cc);
           
       }
       system.debug(cc1.size());
       insert cc1;