Friday, December 21, 2012

Querying sObject Relationships in Apex Programming Language

In Force.com Platform, many objects are related to each other as a parent or child. We call this as parent-to-child and child-to-parent relationships. In our article about sObject, we learnt that sObject in Apex programming language represents an object in Force.com Platform. 

So, just like the objects in Force.com platform, sObject in Apex is also aware of relationships. Let us see this with few examples.

The object Contact is related to the object Account by child-to-parent relationship. Contact is child, Account is parent and relationship name is Account. See the following lines code where it retrieves the Contact sObject and at the same time obtains parent information as well.
   Contact c = [SELECT Id, Name, Account.Name FROM Contact WHERE FirstName='John' LIMIT 1];
   Account a = c.Account;
   System.debug (a.Name);
   System.debug (c.Account.Name);

When we are retrieving the Contact sObject into c, since we are reading Account.Name as part of the query, we are able to read c.Account as Account sObject. Hence able to read the parent account name. In Account.Name in the query, Account is the relationship name.

Now another scenario. The object Account is related to the object Contact by parent-to-child relationship. Account is Parent, Contact is child and relationship name is Contacts. See the following lines of code where it retrieves the Account sObject and at the same time retrieves all its Contacts as children.
   Account a = [SELECT Id, Name, (SELECT FirstName, LastName FROM Contacts) FROM Account WHERE Name='ABC Corp'];
   System.debug (a.Name);
   List <Contact> children = a.Contacts;
   System.debug('Number of contacts: ' + children.size());
   for (Contact c: children) {
   System.debug(c.FirstName);
   }


When we are retrieving the Account sObject into a, we are reading its children Contacts using a sub query. Hence able to extract all its children sObjects into an array and read them out as individual sObject.

Happy cloud computing using Salesforce!

No comments:

Post a Comment