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
Julie Curry 19Julie Curry 19 

soql query on Task object to grab field on custom object in whatID

I am trying to create a soql query and pull in a field from the custom object whose ID appears in the task whatId/'related to' field.

I've tried what resembles the below in the query but nothing is working. Is the fact that whatId is a polymorphic field preventing me from being able to grab the field in the related object? Or can someone tell me how to do this if it's possible?

customobjectname__c.customobjectfield__r
customobjectname__r.customobjectifeld__c
whatId__r.customobjectfield__c

Thank you in advance for your help!
 
AnudeepAnudeep (Salesforce Developers) 
Hi Julie, 

WhatId represents ID of a related Account, Opportunity, Campaign, Case, or custom object. Since WhatId can refer to any number of object types, you can't reference a custom field from a single one of those objects.

You should write multiple queries
 
Task t = [SELECT WhatId FROM Task WHERE Id = 'Task Id']; 

your_Object__c m = [SELECT id FROM My_Object__c WHERE Id =: t.WhatId];

See Relationship Queries to learn more

Anudeep