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
Phuc Nguyen 18Phuc Nguyen 18 

compare field on grand child record to a different grandchild record

Hello All,
Trying to figure out how to compare a grand child record field to another grand child record field

Parent = Merch
Child = Invoice
grand child = invoice Line
Child = Purchase
grand child = Purchase line

I am trying to compare the  merch category field on the invoice Line to the merch category field on the Purchase line.

Purchase is a lookup field on Merch.
Invoice records are related records on Merch.
Need to determine if there is a Purchase lIne record with a merch category value that is the same as the merch category on the Invoice lIne that is being created. 

Just not sure how to query/map the record.

Thank you,
Suraj Tripathi 47Suraj Tripathi 47
Hi Phuc Nguyen

I have tried to solve the query... Please let me know if this is what you are looking for:
public class GrandChildCompare {
    public static void compareGrandChild(){
        set<Id> MerchIds = new set<Id>();
        List<Merch__c> merchData = [Select Id, Name from Merch__c];
        if(merchData.size() > 0){
            for(Merch__c each : merchData){
        Map<Id, List<Invoice_Line__c>> collectionOfInvoiceLineWithMerchId = new  Map<Id, List<Invoice_Line__c>>();
        List<Invoice__c> listInvoice = [SELECT MerchId__c, Id, Name, (SELECT Name, Id FROM Invoice_Lines__r) 
                                        FROM Invoice__c where MerchId__c = :MerchIds];
        for(Invoice__c eachItem : listInvoice){
                collectionOfInvoiceLineWithMerchId.put(eachItem.MerchId__c, eachItem.invoice_Lines__r);
        Map<Id, List<Purchase_line__c>> collectionOfPurchaseLineseWithMerchId = new  Map<Id, List<Purchase_line__c>>();
        List<Purchase__c> PurchaseList = [SELECT Id, Name, MerchId__c, (SELECT Id, Name FROM Purchase_lines__r) 
                                          FROM Purchase__c WHERE MerchId__c = :MerchIds];
          for(Purchase__c eachItem : PurchaseList){
                collectionOfPurchaseLineseWithMerchId.put(eachItem.MerchId__c, eachItem.Purchase_lines__r);
        for(Id eachId : MerchIds){
            system.debug('invoice_Line data with respect to grand parentId : ' + collectionOfInvoiceLineWithMerchId.get(eachId));
            system.debug('Purchase_lines data with respect to grand parentId : ' + collectionOfPurchaseLineseWithMerchId.get(eachId));

If you find the above solution helpful, then please mark it as Best Answer to help others too.

Thanks and Regards,