Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers

up vote 5 down vote accepted

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.

share|improve this answer
add comment

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

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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