[SalesForce] Insert master-detail relationship record in salesforce using apex class

How can i insert a master-detail relationship record in salesforce using
apex class. Below is my code.

I am inserting poll questions first than with respect to its inserted id, I want to insert poll options.

1) LghtCompNS__Poll_Question__c(Master Object),
2) LghtCompNS__Poll_Option__c(Detail Object)

@AuraEnabled
    public static LghtCompNS__Poll_Question__c addPollQuestion(LghtCompNS__Poll_Question__c pollQuest,
                                                               List<string> optionValList) {

        try{

            System.debug('Upsert Start');
            //Upsert poll question.
            upsert pollQuest;        
            System.debug('Question ID'+pollQuest.Id);
            System.debug('Option list' + optionValList);

            Poll_Option__c optionObj = new Poll_Option__c();
            //Add options for respective question.
            /*for(integer optVal=0;optVal<=optionValList.length;optVal++)
            {
                optionObj = new Poll_Option__c(
                    LghtCompNS__Poll_Question__c = pollQuest.Id,
                    Name=string.valueof(optVal)
                );
            }*/

            for(string opt: optionValList){
                optionObj = new Poll_Option__c(
                    LghtCompNS__Poll_Question__c = pollQuest.Id,
                    Name=opt
                );  

            }

            upsert optionObj;                                          

        }
        catch(DmlException e)
        {
           System.debug('An unexpected error has occurred: ' + e.getMessage());          

        }                                                       

        return pollQuest;
    }

Best Answer

You have to add all new options to the List and then insert the list:

List<Poll_Option__c> options = new List<Poll_Option__c>();

for(string opt: optionValList){
    Poll_Option__c option = new Poll_Option__c(
        LghtCompNS__Poll_Question__c = pollQuest.Id,
        Name=opt
    );
    options.add(option);
}

insert options;  
Related Topic