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 ?
Attribution to: vishesh
Possible Suggestion/Solution #1
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);
}
Attribution to: Phil Hawthorn
Possible Suggestion/Solution #2
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
, orWHERE
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.
Attribution to: Alex Tennant
This content is remixed from stackoverflow or stackexchange. Please visit https://salesforce.stackexchange.com/questions/34813