3

Parent__c has many Child__c

Child__c is defined by boolean attribute Checkbox__c.

How do I select all Parents where Child__c.Checkbox__c = true?

The following doesn't work:

Parent__c[] parents = [SELECT Id FROM Parent__c WHERE Child__r.Checkbox__c = true];

1 Answer 1

2

You'll need to query the children records (nested query) and check against the size of the list:

Parent__c[] parents = [SELECT Id, (SELECT Id FROM Children__r WHERE Checkbox__c = true) FROM Parent__c] where Children__r is your child relationship name on the Parent lookup.

Then you need to go through the list and work out which parent has children with checkbox = true:

Parent__c[] parentsMatchCriteria = new List <Parent__c> ();

for (Parent__c parent : parents)
{
    if (parent.Children__r.size() > 0)
    {
        // this parent has children with checkbox__c = true, add it to a list
        parentsMatchCriteria.add(parent);
    }
}
// work with the list - parentsMatchCriteria 

Alternatively, you can start from the children:

Child__c[] children = [SELECT Parent__r.Id, Parent__r.CustomField__c FROM Child__c WHERE Checkbox__c = true]

then iterate through that list and build up the list of parents:

Parent__c[] parentsList = new List <Parent__c> ();

for (Child__c child : children)
{
    Parent__c parent = new Parent__c (Id = child.Parent__r.Id);
    parent.CustomField__c = child.Parent__r.CustomField__c;
    // add the parent sObject instance to the list
    parentsList.add(parent);
}
// work with the list - parentsList
0

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .