0

I have three objects:

Order__c Package__c Account

Package has a relationship with account and order.

Order has a relationship with account.

If a package has an account attached to it, how can I make it also attach to that account’s order?

    Set<Id> accountOnPack = new Set<Id>();
    List<Package__c> packs = new List<package__c>();
    for(package__c package : packages){
        if(package.order__c== null && package.received__c =true ){
            accountOnPack.add(package.get(id).Account__c);
            //query to grab order from accounts?
            // order__c orders = OrderQueries.getOrders(item.account__r.id);
            packs.add(package);
        }
    }

From here I need to add these packages to the account’s order. Where would I go from here? How can I then query for the account's orders and attach it to the packages?

  • Do you want to relate account record in your order which is related to package? – Prem Anandh Aug 7 '18 at 3:47
  • There could be multiple orders attached to an account? If yes, then how would you identify which order needs to be attached to which package? – Naval Sharma Aug 7 '18 at 6:33
  • It would be the most recent order that is in the status" prepared". – adming32442 Aug 7 '18 at 13:42
0

I assume your problem statement is: If Package has Account and The Account have Ordered, then you want to relate that package to the order

   //fetch all Account Id's from the Package records:
   Map<Id, Id> packageToAccountId = new Map<Id, Id>();
   for(package__c package : packages){
    if(string.isBlank(package.Account__c))
        packageToAccountId.put(package.id, package.Account__c);
   }

   //get all orders related to that Account
   //update the Orders__r relationship name accordingly
   Map<Id, Account> accountToOrderId = Map<Id, Account>(List<Account>([Select id, (Select Id from Orders__r where Account__c in :packageToAccountId.values() and package__c = '' limit 1) from Account where id in :packageToAccountId.values()]));

   //process starts here
   List<Package__c> packageToUpdate = new List<package__c>();
   for(package__c package : packages){
    Account currentAccount = accountToOrderId.get( packageToAccountId.get(package.Id) );
    if(package.order__c == null && package.received__c = true ){
        //assuming one account has only one related order. I used Limit 1 in query
        //update Orders__r relationship name accordingly
        if(currentAccount.Orders__r[0] <> null && currentAccount.Orders__r[0] <> '' )
            packageToUpdate.add(new Package__c(id = package.id, Order__c = currentAccount.Orders__r[0]Id));
    }
   }

Please note that the code is not tested but must fulfill your requirement. You have to update the code at some points!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.