0

I want to use accounts and related Opportunities in my LWC.

@AuraEnabled(Cacheable=true)
    public static Account[] getAllAccounts(){
        return [SELECT 
                    Id,
                    Name,
                    (SELECT 
                        Id,
                        Name,
                        CreatedDate,
                        CloseDate,
                        Amount
                    FROM Opportunities)
                FROM Account
                WHERE Opportunities.StageName = 'Closed Won'
                WITH SECURITY_ENFORCED
                GROUP BY Name
                ];
    } 

The problem is that I want to use SUM(Amount) Related to each account but I can't find how to do that. Can you help me?

2 Answers 2

0

I don't think you can aggregate the value of fields on child records using SOQL alone.

You can alternatively try use Opportunity as your source object like this:

List<AggregateResult> result = [SELECT AccountId, SUM(Amount) FROM Opportunity GROUP BY AccountId];

Then parse the results into a map or something, however you need to deal with the data, for example:

Map<Id, Decimal> mappedResults = new Map<Id, Decimal>();
for (Integer i = 0; i < results.size(); ++i) {
    mappedResults.put(Id.valueOf(String.valueOf(results[i].get('AccountId'))), Double.valueOf(results[i].get('expr0')));
}

Then you'd have a map like this:

{0018E00001hc9eJXXX => 5.0, 0018E00001hp4VdYYY => 9.0}

Hopefully this is somewhat helpful, until someone can provide what you're looking for!

0

I decided to make easier. It's just needed to create custom roll-up summary field and retrieve it from apex.

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.