在 SOQL Salesforce 中读取子查询的结果

问题描述 投票:0回答:1

我是 Apex 和 SOQL 的新手。

我想使用 SOQL 从帐户和联系人中获取数据,并将结果提供给列表。

从列表中,我想从结果外部查询帐户和内部查询(来自联系人)中“获取”数据。我该怎么做?

This is what I tried, I do not know how to proceed further.

integer counter = 0;
string accountId;
string accountName;
List<Account> myAccts = [SELECT Id, Name, (Select Id, Name from Contacts) from Account];
for(Account i :myAccts) {
    
    
    //System.debug(i);
  Account currentAccount =   myAccts.get(counter);
    
    accountId = currentAccount.Id;
    accountName = currentAccount.Name;
    System.debug('This is the current account record---' + accountName);
    counter = counter+1;
}
subquery soql
1个回答
0
投票
// SOQL to retrieve Accounts and related Contacts
List<Account> myAccts = [SELECT Id, Name, (Select Id, Name from Contacts) from Account];

// Loop through each Account
for (Account acct : myAccts) {
   
    // Example of referencing Account field
    system.debug(acct.Name);
    
    // Loop through each related Contact
    for (Contact con : acct.Contacts) {
        
        // Example of referencing Contact field
        system.debug(con.Name);
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.