Have one custom object Orders_OMS__c.
Account has two child relationship with it
account.Order_OMS__r
account.Order_OMS1__r
Question:
How to insert list of newly created Orders_OMS__c into
account.Order_OMS__r
or
account.Order_OMS1__r
Below is the code [It always inserts only to one relation account.Order_OMS1__r and not to the other] Note: There are records with orderType.isOMSOrder==true and orderType.isOMSOrder==false
insert newOmsOrders;
if (orderType.isOMSOrder) {
for (Orders_OMS__c omsOrder : newOmsOrders) {
System.debug('adding to account.Order_OMS__r omsOrder.Id ' + omsOrder.Id);
account.Order_OMS__r.add(omsOrder);
}
//account.Order_OMS__r.addall(newOmsOrders);
insert account.Order_OMS__r;
//upsert account.Order_OMS__r;
} else {
for (Orders_OMS__c omsOrder : newOmsOrders) {
System.debug('adding to account.Order_OMS1__r omsOrder.Id ' + omsOrder.Id);
account.Order_OMS1__r.add(omsOrder);
}
//account.Order_OMS1__r.addall(newOmsOrders);
insert account.Order_OMS1__r;
//upsert account.Order_OMS1__r;
}
Attribution to: Zack
Possible Suggestion/Solution #1
Unless you are working with the special case of external ids, the only way to create an association between two objects is using the id fields (that end __c in custom objects) not the relationship fields (that end in __r in custom objects).
The direction of the relationship is not entirely clear to me (as your relationship names are singular and it is helpful to use plurals for the "many" relationship name), but taking my best guess from your code setting the ids would look like this:
for (Orders_OMS__c omsOrder : newOmsOrders) {
if (orderType.isOMSOrder) {
// Corresponds to Order_OMS__r; may have a different name but will end __c
omsOrder.Account__c = account.Id;
} else {
// Correspids to Order_OMS1__r; may have a different name but will end __c
omsOrder.Account1__c = account.Id;
}
}
insert newOmsOrders;
I can only assume that you are seeing one of the relationships being setup because of some code elsewhere in your code base.
I also suggest you:
System.debug('isOMSOrder=' + orderType.isOMSOrder);
to confirm that there are both true and false values.
Attribution to: Keith C
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/30330