I'm trying to create an SOQL query with a subquery to show contacts and accounts located within a state that have a certain custom object relationship:
Here is my code:
public with sharing class AccountsinPlacesExt {
@AuraEnabled
public Place__c place { get; private set; }
public List<Account> inPlaceAccounts { get; private set; }
public AccountsinPlacesExt(ApexPages.StandardController controller)
{
// add the Place__c field that tells you which state
List<String> neededFields = new List<String> { 'City__c','State_Code__c' };
if (!Test.isRunningTest()) controller.addFields(neededFields);
place = (Place__c)controller.getRecord();
if (place.City__c != null) {
// search for city and state match
inPlaceAccounts = [
SELECT Id,Name,Our_Role_Service_Affiliation_for_Account__r,(SELECT Name FROM Contacts) FROM Account WHERE Our_Role_Count__c > 0 AND BillingCity = :place.City__c AND BillingState = :place.State_Code__c AND Id IN (SELECT Account__c FROM Our_Role_Service_Affiliation_for_Account__c WHERE Our_Role__r.Name != 'Outreach')
];
} else {
//search for only state match
inPlaceAccounts = [
SELECT Id,Name,Our_Role_Service_Affiliation_for_Account__r,(SELECT Name FROM Contacts) FROM Account WHERE Our_Role_Count__c > 0 AND BillingState = :place.State_Code__c AND Id IN (SELECT Account__c FROM Our_Role_Service_Affiliation_for_Account__c WHERE Our_Role__r.Name != 'Outreach')
];
}
// end else
}
}
Now I'm still seeing:
I tried but it isn't working now. even in the dev console I'm seeing an error: SELECT Id,Name,Our_Role_Service_Affiliation_for_Account__r
^
ERROR at Row:1:Column:16 No such column
'Our_Role_Service_Affiliation_for_Account__r' on entity 'Account'. If
you are attempting to use a custom field, be sure to append the '__c'
after the custom field name. Please reference your WSDL or the
describe call for the appropriate names.
Best Answer
When you try to filter results based on a separate query, that is called a Left Inner Join.
When you try to pull in parent fields in a
SELECT
clause, it's called a Right Outer Join.You cannot combine these types of join. But you're needlessly complicating things, since
SomeLookup__r.Id
is always the same value asSomeLookup__c
. So in this case, just use that. You also have to remove all other fields, the only field you are allowed to have in aLeft Inner Join
query is the field you are filtering on. So change your join to:Any fields you want to retrieve from the queried records must be in the top-level
SELECT
clause.