function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
mrizmriz 

how to query and use contact id from account object

I want to fetch id of contact person associated with an Account. And then use it in VF page.

SOQL
Account ac=[Select id,name,(select id,phone from Contact) where name='xyz' limit 1];
public ID cId;

This line compiles well.
But i don't how to use store contact Id from "ac" to "cId".

Any help would be highly appreciated.
Query:
Best Answer chosen by mriz
Marek Kosar_Marek Kosar_

It's still a list, with one item.

You can retrieve Id of first related contact in that list: ac.contacts.get(0).Id

All Answers

AshlekhAshlekh
Hi,

1. The below query will give you all contacts which are associated with an account whose name is xyz.
List<Contact> conList = new List<Contact>();
for( Account x:[select id,name,(select id,AccountId ,name from contacts) from account where name = 'xyz' limit 1])
{
  for(Contact con:x.contacts)
  {
    conList.add(con); 
  }
}

syste,.debug('-----'+conList);

2. The below query will give you the contacts who account name is 'XYZ'
List<Contact> conList = new List<Contact>();
conList = [select id ,accountId, name from contact where account.name = 'xyz' limit 999];

system,.debug('-----'+conList);

-Thanks
Ashlekh Gera

 
Marek Kosar_Marek Kosar_
Hi,

you can have multiple contacts related to 1 account, so you have to go through all queried contact, like:
Account ac=[Select id,name,(select id,phone from Contacts) from Account where name='xyz' limit 1];

for(Contact con : ac.contacts){
    //con.Id
}

Marek
mrizmriz
Is there any way to get the Contact ID from this Query itself
Account ac=[Select id,name,(select id from Contacts) from Account where name='xyz' limit 1];

something like -->  ac.contacts.id

Reason being that this query compiles successfully, that perhaps means that id is being fetched from contact.

I only need to get ID of associated Contact without having to query another object (Contact in this case).
 
Marek Kosar_Marek Kosar_
No, and the reason is simple -> you can have multiple contacts related to account, so ac.contacts is list not single record
mrizmriz
What if, i only have one associated Contact?
Marek Kosar_Marek Kosar_

It's still a list, with one item.

You can retrieve Id of first related contact in that list: ac.contacts.get(0).Id

This was selected as the best answer