I need to query all related tasks from a contact (currentRecordId) but my code below shows nothing.
What I'm doing wrong?
Map<Id, TaskRelation> relatedTasks1 = new Map<Id, TaskRelation>([select taskId from TaskRelation where relationId = :currentRecordId]);
system.debug('size relatedtasks1 ' +relatedtasks1.size()); // 3 items
List<Task> listtasks = [select Id, Subject, CreatedDate, Createdby.Name, Owner.Name, RecordType.Name, Status, Who.Name, Who.Id, What.Name from Task where Id IN :relatedTasks1.keySet()];
system.debug('size listtasks ' +listtasks.size()); // 0 items
for(Task a : listtasks) {
wrapperList.add(new Wrapper(a, 'Task'));
}
DEBUG of map relatedtasks1
09:36:49:197 VARIABLE_ASSIGNMENT
[23]|relatedTasks1|{"0RT1x0000094HFHGA2":{"TaskId":"00T1x00000CSmgFEAT","Id":"0RT1x0000094HFHGA2"},"0RT1x0000094HEeGAM":{"TaskId":"00T1x00000CSmdSEAT","Id":"0RT1x0000094HEeGAM"},"0RT1x0000094HF8GAM":{"TaskId":"00T1x00000CSmgAEAT","Id":"0RT1x0000094HF8GAM"}}|0x3964be86
Debug of list Listtasks
09:36:49:199 SOQL_EXECUTE_BEGIN [24]|Aggregations:0|SELECT Id,
Subject, CreatedDate, Createdby.Name, Owner.Name, RecordType.Name,
Status, Who.Name, Who.Id, What.Name FROM Task WHERE Id = :tmpVar1
09:36:49:206 SOQL_EXECUTE_EXPLAIN [24]|Index on Task : [Id], cardinality: 3, sobjectCardinality: 29, relativeCost 0.333
Best Answer
the problem is with
Map<Id, TaskRelation> relatedTasks1 = new Map<Id, TaskRelation>([select taskId from TaskRelation where relationId = :currentRecordId]);
when you are passing into the constructor of the
Map
a list of sobjects, the key is set to record id. In this example, it isTaskRelation.Id
In the next line
List<Task> listtasks = [select Id, Subject, CreatedDate, Createdby.Name, Owner.Name, RecordType.Name, Status, Who.Name, Who.Id, What.Name from Task where Id IN :relatedTasks1.keySet()];
Task
records are filtered byTask.Id
, but key set returnsTaskRelation.Id
set. So even not proper sobject ids are used. Sрould be ids ofTask
, but сгккутедн ids ofTaskRelation
.There is one step that is missing. Getting from
relatedTasks1
TaskId
field values. Your code should look like this:Moreover, it is possible to do it in one query using a nested query:
Or you can query needed info also using a parent relationship: