+ Start a Discussion
nikvmnikvm 

Child To Parent SOQL

Hello All,

 

I have below query  which works fine

NotesList  = [SELECT ParentId, CreatedById, CreatedDate, parent.id, parent.name FROM Note ];

 

however when I add one more column to this it fails.as below 

NotesList  = [SELECT ParentId, CreatedById, CreatedDate, parent.id, parent.name, parent.AccountNumber FROM Note ];

 

I get the error ----> no such column ' account number ' on entity name ***************

 

Please help me rectify the same.

 

Thanks 

 

sfdcfoxsfdcfox
You can't query a polymorphic key's related values except those in common to all objects: Id, and Name. Instead, you'll have to construct a second query to query the accounts you would like to retrieve.
Satish_SFDCSatish_SFDC
As sfdcfox pointed out, Note can look up to many objects.
If you are sure the parent is an Account object, you write another query to retrieve the account number.

accountNumber = [Select AccountNumber From Account WHERE ID = <the parent id found in the previous query>];

Ideally you bulkify the code but this is just a sample.

Hope this helps.

Regards,
Satish Kumar
Please mark my answer as a solution if it was helpful so it is available to others as a proper solution.
If you felt I went above and beyond, please give me Kudos by clicking on the star icon.
souvik9086souvik9086

In addition to the ways mentioned above there is another way. You can do SOQL Polymorphism relationship query as well.

Something like this

 

SELECT ID,
TYPEOF Parent
WHEN Account THEN AccountNumber
END
FROM Note

 

You can refer here

http://blogs.developerforce.com/tech-pubs/2012/09/soql-polymorphism-or-how-i-learned-to-love-the-polymorphic-relationship.html

 

If the post helps you please throw KUDOS.

Thanks

sfdcfoxsfdcfox
Except it's apparently still in preview. But that's a good point for future code. You would still need to use dynamic apex field references though, I would think. I look forward to seeing that feature released generally.