function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rafael.Martins.SantosRafael.Martins.Santos 

How get a parent data from a child object?

Hi,

I have a custom object child of the opportunity object.
I want make a SOQL from the child to get the data of the Opportunity.
Someone know how I do that?
Some best practice in this case.

Thanks

Rafael
Best Answer chosen by Rafael.Martins.Santos
Ashish KumarAshish Kumar
Hi Rafael,

You will have to replace the Opportunity__r with the field api name for example the api of the field is opp__c then use as opp__r.Name to get the opportunity name.

Hope this clears the thing.

Please let me know if it solves the problem.

Regards,
Ashish Kr.

All Answers

Ashish KumarAshish Kumar
Hi Rafael,

You could use child - parent soql as below
For(Contact c:[select Name,Account.Name from Contact])
{
  system.debug('Contact Name :'+ c.Name +'   Account Name:' +c.Account.Name);
}

Please go through below link to read more about relationship queries.

https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_relationships_query_using.htm

Regards,
Ashish Kr.
Rafael.Martins.SantosRafael.Martins.Santos
Hi Ashish,
I tried to use the example that you wrote, but this not work.
SOQL I tried to use:
SELECT Id, Name, Opportunity.Name FROM item_da_Oportunidade__c

The link that you share with me, only shown the Nested SOQL from Parent to Child.
Ashish KumarAshish Kumar
Hi Rafael,
 Just try the below SOQL:
SELECT Id, Name, Opportunity__r.Name FROM item_da_Oportunidade__c
Regards,
Ashish Kr.

 
Rafael.Martins.SantosRafael.Martins.Santos
No,
I'm still getting an error
ERROR at Row:1:Column:18
Didn't understand relationship 'Opportunity__r' in field path. If you are attempting to use a custom relationship, be sure to append the '__r' after the custom relationship name. Please reference your WSDL or the describe call for the appropriate names.
Ashish KumarAshish Kumar
Hi Rafael,

You will have to replace the Opportunity__r with the field api name for example the api of the field is opp__c then use as opp__r.Name to get the opportunity name.

Hope this clears the thing.

Please let me know if it solves the problem.

Regards,
Ashish Kr.
This was selected as the best answer
Rafael.Martins.SantosRafael.Martins.Santos
Hi Ashish,
Now I get it.
I have to use the custom field that make the relationship with my parent object, so then it will work.
As you say, my custom field is Oportunidade__c, so I use Oportunidade__r.Name and I could access the data of my parent object.
Thanks Ashish for your help.