0

I have a vfp that brings the contact data of an opportunity. I'm going to call it contact X, and for that I do a select on the object "OpportunityContactRole" and use a lookup field to get data from the contact X "contact.".

But I also need to reach the fields of another contact, and I'm going to call contact Y. For that I created a new lookup field, but how can I make the call?

I still get confused a lot in the relationship of objects...

Controller:

public List <OpportunityContactRole> getAvalist(){ 
         if(avalista==null){
             avalista=[SELECT Id,contactId, contact.Name,contact.CPF__c,contact.MailingCity,contact.MailingStreet,contact.MailingState,
                       contact.MailingPostalCode, contact.Procurador_do_Contato__c.CPF__c//this is my last try..I thought of something like contact.Procurador_do_Contato__c.contact.CPF__c...
                       FROM OpportunityContactRole 
                       WHERE OpportunityId =: idOpp
                      ];
         }  
       
2
  • 1
    What is "a vfp"?... A Visual FoxPro database? Mar 9, 2022 at 4:12
  • 1
    @PeterMortensen It's a pretty common abbreviation for "VisualForce Page"
    – Derek F
    Mar 9, 2022 at 13:11

1 Answer 1

2

When you have a custom relationship field, and want to query/access data on the related (parent) record, the __c at the end of the relationship field needs to change to __r

So instead of what you have

[SELECT Id, contactId, contact.Name, contact.CPF__c, contact.MailingCity, contact.MailingStreet, 
    contact.MailingState, contact.MailingPostalCode, contact.Procurador_do_Contato__c.CPF__c
FROM OpportunityContactRole
...
]

you'd use Procurador_do_Contato__r instead

[SELECT Id, contactId, contact.Name, contact.CPF__c, contact.MailingCity, contact.MailingStreet, 
    contact.MailingState, contact.MailingPostalCode, contact.Procurador_do_Contato__r.CPF__c
FROM OpportunityContactRole
...
]

In a way, this is also similar to what we do with standard relationship fields. E.g. ContactId changes to Contact (the 'Id' part is dropped) when we want to access related data.

Accessing it in Apex follows the same pattern.

System.debug(myOppContactRole.Contact.CPF__c);
System.debug(myOppContactRole.Procurador_do_Contato__r.CPF__c);
2
  • 2
    The mnemonic that I've used in the past works in English, but I'm not sure how helpful it'd be to others, so I left it out of the main answer. That mnemonic is "I'm not looking for a __custom field, I want __related data"
    – Derek F
    Mar 8, 2022 at 19:20
  • 1
    wow, thanks for the help and explanations! @Derek F
    – Souza
    Mar 8, 2022 at 19:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .