Payment1 and Payment2 has a lookup relationship with Case. Now I need to write a SOQL to get call its child object dynamically. Case could have record for Payment1 or Payment-2 or both Payment-1 and Payment-2.

List<Case> caseList = [Select Id,OwnerId, (select Id, OwnerId, CreatedById from Payment__r), 
                                        (select Id,OwnerId,CreatedById from Payment_2__r) 
                                         FROM Case 
                                         WHERE Id IN :newCasesMap.keySet()];

How to identify the Payment-1 only present or Payment-2 only present or both Payment1 and Payment-2 present ?

1 Answer 1


Keeping the query you already have, the code could look like this:

for (Case c : caseList) {
    Boolean p1 = c.Payment__r.size() > 0;
    Boolean p2 = c.Payment_2__r.size() > 0;
    if (p1 && p2) {
        // Add code for both present
    } else if (p1) {
        // Add code for p1 only present
    } else if (p2) {
        // Add code for p2 only present
    } else {
        // Add code for neither present

Note that the relationship name from parent to child normally defaults to a plural; if that is the case here the names would be Payments__r and Payment_2s__r.

If you don't need the payment records and just want to count them, you could use an aggregate query instead.

  • Hey thanks ! I want to also get the Payment__r and Payment_2__r records and create share object for them..
    – Kanika
    Jan 17, 2018 at 9:45
  • @Kanika Your query already has those records in the lists, just iterate over them and create the share records.
    – sfdcfox
    Jan 17, 2018 at 9:48
  • Sometime for ex: Payment_2__r doesnot have any records to its breaking here Boolean p2 = c.Payment_2__r.size() > 0;
    – Kanika
    Jan 17, 2018 at 9:52
  • @Kanika If there are no records an empty list is returned so that test should still work. Exactly what error are you seeing?
    – Keith C
    Jan 17, 2018 at 10:00

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.