1
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 ?

3

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.

3

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);
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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