Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.
String queryFields = 'Id, AccountId, ContactId, type';
List<Case> cases = Database.query('select '+ queryFields +' from Case');
for(Case c: cases){
     System.debug(c.AccountId);
}

Instead of account id here I want account name. I don't want to do query in for loop for each case. is there a way I can make user of AccountId reference to get account name ?

share|improve this question

2 Answers 2

up vote 3 down vote accepted

Simply add Account.Name to your query. You can traverse up to 2 levels of relationships in a SOQL query this way.

You can query the following relationships using SOQL:

Query child-to-parent relationships, which are often many-to-one. Specify these relationships directly in the SELECT, FROM, or WHERE clauses using the dot (.) operator. For example:

SELECT Id, Name, Widget__r.Name
FROM Model__c
WHERE Widget__r.CreatedBy.LastName LIKE 'Smi%'

This query returns the ID and name for only the contacts whose related account industry is media, and for each contact returned, the account name.

Relationship Queries are covered in more detail in the documentation.

share|improve this answer
    
Thanks for the detailed answer –  vishesh May 10 at 8:57

It should be as simple as this:

String queryFields = 'Id, AccountId, Account.Name, ContactId, type';
List<Case> cases = Database.query('select '+ queryFields +' from Case');
for(Case c: cases){
     System.debug(c.Account.Name);
}
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.