how to update the subquery fields ? salesforce, soql, apex

Go To StackoverFlow.com

0

Here is the query which will get me all the contacts have HD quality orders.

`Orderc__c[] orders = [SELECT id,customer__c, Customer__r.Number_of_HD_Orders__c,` `Quality_Code__c FROM Orderc__c where Quality_Code__c='HD'];`

then I change use these code to update the number of HD orders for each contact:

for(Orderc__c o: orders){
    if(o.Customer__r.Number_of_HD_Orders__c==null)
    o.Customer__r.Number_of_HD_Orders__c=0.0;
    o.Customer__r.Number_of_HD_Orders__c++;
}

now, the question is how can I update the contacts. as "update orders;" will not update the contacts.

2012-04-04 04:19
by Lee Fang


0

You just need to add all the contacts to a new collection and then update that:

map<Id, Contact> contacts = new map<Id, Contact>();

for(Orderc__c o: orders) {
    if(o.Customer__r.Number_of_HD_Orders__c == null) {
        o.Customer__r.Number_of_HD_Orders__c=0.0;
    }

    Contact sContact = contacts.get(o.Customer__c);

    if(sContact != null) {
        sContact.Number_of_HD_Orders__c++;
    } else {
        o.Customer__r.Number_of_HD_Orders__c++;
        contacts.put(o.Customer__c, new Contact(id = o.Customer__c, Number_of_HD_Orders__c = o.Customer__r.Number_of_HD_Orders__c));
    }
}

update contacts.values();

Note this is very rough, doesn't check for too many contacts in an update etc., but it should get your thinking in the right direction!

2012-04-04 04:57
by Matt Lacey
Thanks for the information. but your code will cause the error: duplicate id in list. I don't know why it does not allow duplicate id in a list(not a set). I think this is causes by some contacts have multiple HD orders. so how could i fix this - Lee Fang 2012-04-04 05:17
Use a map instead of a list, before adding the contact to the map, see if it exists in there already. If it does, increment that one, otherwise add it. Then just update the maps' values: update mymap.values();Matt Lacey 2012-04-04 05:29
nvm, I simple need to add the contacts to a set, then add the set to a list. and update the list. as DML only works for list not set - Lee Fang 2012-04-04 05:30
You might not get the right count if you use a set, if they have two orders (and so appear twice) you'll only increment their counter once! Better to do it with a map : - Matt Lacey 2012-04-04 05:33
yes, you are right. so I used two loops. one for calculating the number, and the other for adding the contact to the set. using map is more tidy but I have a small brain. :( Thanks, really appreciated - Lee Fang 2012-04-04 05:49
It's all just practice — the more you do, the more you learn and the more techniques you remember - Matt Lacey 2012-04-04 06:45
Ads