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
JJ1234JJ1234 

Query other related items of the same object from the current related item's Master object--SOQL

Hello,

I'm relatively new to SOQL and Conga Query builder and am attempting to query related data of the same object, using a lookup of the current object. Here is how the objects are related:

From the current Custom object, I have a lookup relationship to accounts--the field is Primary Account. I'd like to query all other related objects of the same type as the current object. My statement looks like this so far, however, it is failing.

SELECT Custom_Field1__c, Name FROM Custom__c WHERE Primary_Account__r.Id = Primary_Account__c.Id

Primary_Account__r.Id is the ID of the Master "Primary Account" on the Custom record, but the query doesn't seem to be pulling the Id to match from the current custom object so that the query can pull all related Custom_Field1 and Name fields from the other custom objects related to the Primary Account. I hope this all makes sense.

Thank you in advance.
JJ1234JJ1234
I'm trying to traverse from child to parent and then query all of the children of the same object from the parent.
sachinarorasfsachinarorasf
Hi Joseph Jankowski,

This just an example of how the parent-child query works.
Ways of writing Parent-Child Queries for Standard Objects
//query from parent to child
Select Id, Name, (Select Id, LastName from Contacts where Lastname='Frank') from Account
//query from child to parent 
Select Id, LastName, Account.Name from Contact
Ways of writing Parent-Child Queries for Custom Objects
//query from parent to child
Select Id, Name, (Select Id, Name from Custom__c ) from Primary_Account__c
//query from child to parent
Select Id, Name, Primary_Account__r.Name from Custom__c
SELECT Custom_Field1__c, Name FROM Custom__c WHERE Primary_Account__r.Id = Primary_Account__c.Id
The above query is yours which you mention.
You can't use a where clause like above.
Have a look at the following for the right way to query:
Primary_Account__c primaryAccount = [select Id from Primary_Account__c Limit 1];
List<Custom__c> customList = new List<Custom__c>();
customList = [Select Id, Name, Primary_Account__r.Name from Custom__c where Primary_Account__c =: primaryAccount .Id];
I hope you find the above solution helpful. If it does, please mark it as the Best Answer to help others too.
Thanks and Regards,
Sachin Arora
www.sachinsf.com