Account acc;
if(o.AccountId!=null) {
    acc = [select id,GUP_GUID__c,OwnerId 
           from Account 
           where Id = : o.AccountId];

List<ECP__c> ecpList = [select id 
                        from ECP__c 
                        where Account__c = :acc.GUP_GUID__c 
                        AND OwnerId= :o.OwnerId 
                        AND Status_Internal__c='Active'];

if(ecpList.size()>0) {
    ECP__c ecp = ecpList[0];
    o.WCSS_ECP__c = ecp.Id;
    update o;

Instead of getting the account first from Opportunity, is there a way to get Account out of Opportunity o directly in the ECP__c query(second one)?

  • I believe your code is incomplete, it looks like you may have missed a few lines. There is no Opportunity o that you refer to a few times. I assume this might all be wrapped in a for loop, but don't want to make assumptions. If you could add the rest it would be helpful. – Chris Duncombe Aug 21 '14 at 19:18
  • 1
    Also, what context are you doing this in? Are you performing a query to get the opportunity, if so then yes we can help you get the account data in that same query, if it is in a trigger on the opportunity, you will still have to perform an additional query to get the account data – Eric Aug 21 '14 at 19:29
  • The use case is that I need to get a list of ECP__c(custom object) where ECP__C account__c = opportunity.account.GUP__GUID__c and OwnerId=o.OwnerId and Status='Active' .. I am passing Opportunity as an parameter to this method. And I want to refer opportunity.Account.GUP_GUID__c directly from opportunity and not get query the account first by opportunity account id – user10930 Aug 21 '14 at 19:59

as @eric already mentioned, you have 2 options based on from where and how you are getting the Opportunity object that you pass into the method..

  1. if you are querying your opportunity before passing into the method, include the field Account.GUP__GUID__c into your query.. something like this

    Opportunity opp = [Select Id, Name, Account.GUP__GUID__c from Opportunity where id = 'yourOppId' limit 1];

2 (a). but if you are calling this method from an opportunity trigger then you cannot directly access related object fields using Trigger.New, So you need to perform the additional query to get the related Account field

2 (b). you can create a custom formula field on the Opportunity to get the GUP__GUID__c field value from Account into the Opportunity so that you can directly access the field

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.