LoginSignup
2
2

More than 5 years have passed since last update.

【Salesforce初心者】SOQLで親リストから子供レコードの取得

Last updated at Posted at 2017-04-06

SOQLの練習をしている時に、詰まったところをメモします。

Trailheadに下記のコードがありました:

Account[] acctsWithContacts = [SELECT Name, (SELECT FirstName, LastName FROM CONTACTS)
                              FROM Account
                              WHERE Name = 'SFDC Computing'];
System.debug(acctsWithContacts);

Contact[] cts = acctsWithContacts[0].Contacts;
System.debug('Name of first associated contact: '
             + cts[0].FirstName + ', ' + cts[0].LastName);

ここの記載が最初理解できなかったです:

Contact[] cts = acctsWithContacts[0].Contacts;

AccountリストからContactリストを受け取る時、なんで「0」を書く必要があるかが最初わからなかったです。

インドの同僚に聞いて、やっとわかりました。

つまり、親リストの中に、内部クエリで子リストをとってきた場合のリスト構造はこうなります(多分)

accountA
-AccountA.Contact1
-AccountA.Contact2
accountB
-AccountB.Contact1
-AccountB.Contact2
-AccountB.Contact3

つまり二次元リストです!

だから Contact[] cts = acctsWithContacts[0].Contacts
でAccountリストの中の1子目のAccountにぶら下がっているContactリストを全部とります。

検証として、いかのコードで検証してみました:
*前提:Account "SFDC Computing"に、二つContactを追加している状態

Account[] acctsWithContacts = [SELECT Name, (SELECT FirstName, LastName FROM CONTACTS)
                              FROM Account
                              WHERE Name = 'SFDC Computing'];
System.debug(acctsWithContacts);
System.debug(acctsWithContacts.size());//これの結果が1

Contact[] cts = acctsWithContacts[0].Contacts;
System.debug(cts.size());//これの結果が2

System.debug('Name of first associated contact: '
             + cts[0].FirstName + ', ' + cts[0].LastName);

System.debug('Name of first associated contact: '
             + cts[1].FirstName + ', ' + cts[1].LastName);
2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2