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
MoTownMoTown 

Parent object custom fields of Attachment SOQL query

I am using dataloader to export Attachment content associated to a particular object.  Is there any way to pull in custom fields from the the polymorphic relationship when filtering on a specific parent type?

I would like to do something like this:
SELECT
	Id, 
	Name, 
	ParentId, 
	Parent.MyCustomField__c,
	Body 
FROM Attachment 
WHERE Parent.Type = 'MyCustomObject__c'

But this returns the error:
No such column 'MyCustomField__c' on entity 'Name'.

I have tried experimenting with TypeOf with no luck:
SELECT 
	Id, 
	ParentId, 
	TYPEOF Parent 
		WHEN MyCustomObject__c 
		THEN MyCustomField__c 
	END, 
	Name,
	Body
FROM Attachment 
WHERE ParentID IN (SELECT id FROM MyCustomObject__c)

This seems to skip the MyCustomField__c column but returns the other columns.

Is there anyway to do this with one SOQL statement?

Thanks,
​​​​​​​
Deepali KulshresthaDeepali Kulshrestha
Hi,

Greetings to you!

you can follow the below link to write soql of polymorphic relationship.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_polymorphic_relationships.htm
https://developer.salesforce.com/docs/atlas.en-us.soql_sosl.meta/soql_sosl/sforce_api_calls_soql_select_typeof.htm

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

Thanks and Regards,
Deepali Kulshrestha
www.kdeepali.com
MoTownMoTown
I have already reviewed that documentation, thanks.
Chuck TomlinsonChuck Tomlinson
I'm sure you've figured this out by now but check field-level security and/or View All Data system permission..