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
Mehul pMehul p 

How to query for Task and their Task relations contacts?

Hi guys,
 
        I am stuck on this problem where I want to loop through task id and their task relation contacts ids. I am not sure how to do it. 
 
List<Contact> relatedContacts = [select id,Last_Activity_Subject__c,
                                                 (select id,Subject from Tasks Order By ActivityDate DESC LIMIT 1)
                                                                      from Contact where id in:ContactIds];
                
        
                for (Contact relatedContact : relatedContacts)
                    {
                        relatedContact.Last_Activity_Subject__c = relatedContact.Tasks[0].Subject;

                    }
                    update relatedContacts;
this code I have it does not update properly for the task relation names. 

Thank you!
 
Ajay K DubediAjay K Dubedi
Hi Mehul,

You can use the below code.
 
public class GetTasks {
    
    public static void getTaskRelatedContact(List<Contact> contactList){
        
        try{
            if(contactList.size() > 0){
                Set<Id> contactIds = new Set<Id>();
                for(Contact contactObject : contactList){
                    contactIds.add(contactObject.Id);
                }
                List<Task> taskList = new List<Task>();
                taskList = [SELECT Id, Subject FROM Task WHERE WhoID IN : contactIds LIMIT 50000];
                System.debug('taskList-->>'+taskList);
            }
        }catch(Exception exp){
            System.debug('Exception Cause-->'+exp.getMessage()+'Line Number-->>'+exp.getLineNumber());
        }
    }
}

You can change the code accordingly.


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

Thanks and Regards,
Ajay Dubedi
www.ajaydubedi.com