Find your content:

Search form

You are here

Accessing OpportunityHistory in a SOQL query

 
Share

My query:

    List<Opportunity> opps = [SELECT id, Probability, LastModifiedDate, OwnerId,
            (SELECT StageName,Probability,SystemModstamp FROM OpportunityHistories order by SystemModstamp desc) 
            FROM Opportunity 
            where LastModifiedDate = LAST_N_DAYS:7];

Then I do:

    for (Opportunity opp:opps) {
        List<OpportunityHistory> histories = opp.OpportunityHistory__r;
                    // ...
                    // ...

This gives me:

Save error: Invalid field OpportunityHistory__r for SObject Opportunity

How do I access the OpportunitiyHsitory objects?


Attribution to: dublintech

Possible Suggestion/Solution #1

If you are accessing OpportunityHistories as a sub-query in SOQL, you would also access in the same way in Apex, e.g.

List<OpportunityHistory> histories = opp.OpportunityHistories 

The __r suffix is for custom object relationships only.


Attribution to: Phil Hawthorn

Possible Suggestion/Solution #2

Use the relationship name, in case of OpportunityHistory this isn't with __r because it is a default salesforce object, in your case this will be

or (Opportunity opp:opps) {
        List<OpportunityHistory> histories = opp.OpportunityHistories;
                    // ...
                    // ...

If you want to find out the name of the relationship, you can perfectly find it by going to the salesforce.schema file in Force.com IDE, go to (in this case) Opportunity, Child Relationships, OpportunityHistory, there you'll find the relationshipname

Screenshot


Attribution to: pjcarly
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/5337

My Block Status

My Block Content