[SalesForce] get account name from a soql query on case

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 ?

Best Answer

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.

Related Topic