0

I have a custom object for example, Field__c. Field Object has a look up to object called Rule__c and Rule__c has related list of Rule_Set__c Object.

I have a SOQL query for fields in Field__c and along with that I need the related list (Rule sets) of the lookup object Rule__c.

My query:

[SELECT Id, Name, Rule__c, Rule__r.Name FROM Field__c]

In the above query I can query field in look up object like: Rule__r.Name. But how can I get the list and the fields (Rule_Set__c) related to Rule__c ?

0

Instead of querying on Field__c object, query on Rule__c object. SOQL query for your requirement can be something like this:

SELECT Field__c, Field__r.Name, Id, Name, <Place any additional fields here>, (SELECT Id, <Place the fields here> FROM Rule_Set__r) FROM Rule__c.

You may also include a where clause on the above query, if need (as shown below):

WHERE Field__r.Name = '<Parent Value>' AND Name = '<Child value (Rule__c object)>'

You can traverse upto 5 level above when querying from child to parent and 1 level down when querying from parent to child.

The usability and performance of this query would depend on your requirement and the query result count.

0

Here's how you can achieve the results in one query

List<Rule__c> results = new List<Rule__c>();
    
    results = [Select Id, Name, (Select Id, Name FROM Rule_Sets__r ) FROM Rule__c 
    WHERE Id IN (Select Rule__c From Field__c)];
    
    system.debug('>> ' + results);

Please add fields as well as WHERE clauses wherever applicable based on your requirements. Also verify if relationship names are correct in the query, if not please change them and retry.

I hope this helps.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.