Salesforce, for one reason or another, doesn't allow us to make relationship fields that target OLI (OpportunityLineItem).
We can hold an OLI Id in a text
field, but that won't allow you to traverse the relationship in SOQL.
Your options here are to break this into two queries (one to pull your Custom_Object__c
records based on the Ids of the OLIs you are working with, one to pull the OLIs and related data from their Opportunities), or maintain a relationship field on MyObject__c
to Opportunity
so you can use two parent-child subqueries (left outer joins).
The two queries method might look like this:
// You'll want this to be a map so that you can easily grab the appropriate OLI when you're
// working with MyObject__c records.
// To get Opportunity data in a query on OLI, you use Opportunity.<field api name> for each field
// The relationship between OLI and Opportunity is a standard field, OpportunityId.
// The child relationship name for standard relationship fields is usually just <object name>, e.g. Opportunity
// (we drop the "Id" bit from the field name)
Map<Id, OpportunityLineItem> olisMap = new Map<Id, OpportunityLineItem>([SELECT Id, UnitPrice, Opportunity.Amount, Opportunity.AccountId FROM OpportunityLineItem WHERE Id IN :oliIds]);
List<MyObject__c> myObjs = [SELECT Id, OtherField__c FROM MyObject__c WHERE OpportunityLineItem_Id__c IN :olisMap.keySet()];
The one query approach might look like this:
// This approach also uses what Salesforce calls a semi-join
// Basically, a subquery in the WHERE clause that tells us what to query in the main query)
// I assume MyObjects__r is the child relationship name between MyObject__c and Opportunity,
// you'll likely need to change this.
// Newlines here are just for readability
List<Opportunity> oppsList = [
SELECT
Id, Amount,
(SELECT Id, UnitPrice FROM OpportunityLineItems__c),
(SELECT Id FROM MyObjects__r)
FROM Opportunity
WHERE Id IN (SELECT OpportunityId FROM OpportunityLineItem WHERE Id IN :oliIds)];
If you need to return a custom field value from parent object, simply reference the Lookup/Master-Detail field's API name and change the __c
to __r
.
If your lookup field API name is Contact__c
, then use Contact__r.somefield
For example:
Select Name, Contact__r.Name , Contact__r.Account.Name
From Pension_Contract__c
Where Signing_Status__c = 'Completed'
Best Answer
I don't think there is a child relationship SocialPersonas available.
Follow these steps, to see the ones available
To find the API name you need to use in your SOQL query:
For example, for the child relationship CaseMilestone, the relationshipname is: "CaseMilestones", in a SOQL query I would use it like this:
[SELECT Id, (SELECT Id FROM CaseMilestones) FROM Case];
. For custom objects you would see the __r appended to the child relationshipname right there, just as you would need to use it a SOQL query.