[SalesForce] Querying Related objects using Partner Api

I'm experimenting with relationship queries using the partner wsdl. The docs say:

"The partner WSDL does not contain the detailed type information available in the enterprise WSDL to get the information you need for a relationship query. You must first execute a describeSObjects call, and from the results, gather the information you need to create your relationship query:

  • The relationshipName value for one-to-many relationships, for
    example, in an account object, the relationship name for the asset
    child is Assets.
  • Use the reference fields available for the relevant object, for
    example, whoId, whatId, or ownerIdon a lead, case, or custom object."

I can't make this into sense. Let's make things specific so they are easier to follow. Say I want to run one of the example queries relating accounts and contacts from the docs. describeSObject on Account gives me a childRelationship[] that shows me that I've got one relating AccountId and Contact called "Contacts". So how do I build this up into a query? Where do I put my relationshipName? It doesn't seem to be included in any of the examples.
An example in the docs:

SELECT Id, FirstName, LastName, AccountId, Account.Name 
FROM Contact 
WHERE Account.Name LIKE ’Acme%’

I can't run this query, because I get a MALFORMED_SQL error about not being able to query relationships.

That note at the end of the doc page quote above makes me think that I can, if only I could build up thequery correctly. Any advice?

Best Answer

Before you deep dive into Describe calls and SOQL you might want to catch up reading about relationships in general. It's a long read and you'll probably frown that you know most of it already but it'll make your knowledge bit more systematic. You might also want to play with queries in Force Explorer, Eclipse or similar SOQL tool. That way you'll know what's the result you're after and describes will only get you there with proper column and rleationship names.

If you have a background with normal relational databases (LEFT JOIN etc) - it all depends from which side you'll start the join.

This will give you all Contacts (including those without Account):

SELECT Id, FirstName, LastName, Email, AccountId, Account.Name FROM Contact

This will give you all Accounts (including these that don't have any Contacts)

SELECT Id, Name, (SELECT Id, FirstName, LastName, Email FROM Contacts)

By applying WHERE clause you can limit the results so the end result could be similar in both cases (all depends on which side of relation you're more interested in...).

Check these for more goodies: How can i get the id of the max record?, REST API query to get all accounts which have child records?

Related Topic